First time here? Check out the FAQ!

Ask Your Question
0

how to use key as index in nested dictionary?

asked 5 years ago

Nagarjun gravatar image

updated 5 years ago

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?

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
0

answered 5 years ago

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...

Preview: (hide)
link
0

answered 5 years ago

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: {}}
Preview: (hide)
link

Comments

can i use this using for loop?

Nagarjun gravatar imageNagarjun ( 5 years ago )

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 ( 5 years ago )

Thank You.

Nagarjun gravatar imageNagarjun ( 5 years ago )

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: 5 years ago

Seen: 243 times

Last updated: Nov 05 '19