Ask Your Question
0

how to use key as index in nested dictionary?

asked 2019-10-29 01:48:31 -0600

Nagarjun gravatar image

updated 2019-11-05 08:54:07 -0600

Iguananaut gravatar image

If I have A={1:{2:3,4:2},2:{}}, and I want to add elements to A[1]. How to add here?

edit retag flag offensive close merge delete

2 answers

Sort by » oldest newest most voted
0

answered 2019-10-29 09:06:16 -0600

Emmanuel Charpentier gravatar image

Alternative solution:

sage: D={1:{2:3,4:2},2:{}}
sage: D[1].update({5:'smile'})
sage: D
{1: {2: 3, 4: 2, 5: 'smile'}, 2: {}}

Possibly more readable...

edit flag offensive delete link more
0

answered 2019-10-29 03:32:04 -0600

FrédéricC gravatar image

Like that

sage: A={1:{2:3,4:2},2:{}}
sage: A[1][5]='smile'
sage: A
{1: {2: 3, 4: 2, 5: 'smile'}, 2: {}}
edit flag offensive delete link more

Comments

can i use this using for loop?

Nagarjun gravatar imageNagarjun ( 2019-10-29 03:35:08 -0600 )edit

Sure you can use a loop; for instance:

sage: A={1:{2:3,4:2},2:{}}
sage: for key, value in A.items():
....:     value[5] = key^2
....:     
sage: A
{1: {2: 3, 4: 2, 5: 1}, 2: {5: 4}}
eric_g gravatar imageeric_g ( 2019-10-29 05:17:54 -0600 )edit

Thank You.

Nagarjun gravatar imageNagarjun ( 2019-10-29 05:51:45 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2019-10-29 01:48:31 -0600

Seen: 37 times

Last updated: Nov 05