Ask Your Question
0

how to use key as index in nested dictionary?

asked 2019-10-29 07:48:31 +0200

Nagarjun gravatar image

updated 2019-11-05 15:54:07 +0200

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 15:06:16 +0200

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 09:32:04 +0200

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 09:35:08 +0200 )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 11:17:54 +0200 )edit

Thank You.

Nagarjun gravatar imageNagarjun ( 2019-10-29 11:51:45 +0200 )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 07:48:31 +0200

Seen: 196 times

Last updated: Nov 05 '19