If I had a sample dict:
mydict = {1:{2:'A'}}
how can I add new data to key 1
so that it can be like:
mydict = {1:{2:'A'},{3:'B'}}
When I do mydict.update({3:'B'})
I get: {1: {2: 'A'}, 3: 'B'}
not {1: {2: 'A'}, {3: 'B'}}
If I try .update
using the same key it just replaces the data:
mydict.update({1:{3:'B'}})
becomes {1: {3: 'B'}}
There already have a good library for you:
from collections import defaultdict
d = defaultdict(dict)
d['person']['name']='frank'
d['person']['age']='age'
and then you can easily get the data from your 2 key! like:
print d['person']['name']
When you do mydict.update({3:'B'})
you are updating the wrong dictionary.
It looks like you want to update the dictionary in mydict[1]
This is assuming you actually want a result of {1: {2: 'A', 3: 'B'}}
as your example {1: {2: 'A'}, {3: 'B'}}
is not valid python.
So try mydict[1].update({3:'B'})
只需添加
mydict[1].update({3:'B'})
mydict ={2:'a',3:'b'} d={1:mydict} print (d) {1: {2: 'a', 3: 'b'}} to update more key:values you can add to mydict
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.