What I want is this:
Dic = {'name':{'id':[1,2,3]}}
I have seen answers of how to do this but the ones I saw required the list to be known when they are inserting. the problem I have is I don't know when I'll have to insert in Dic['name']['id']
.
Is there a way to make something like this Dic['name']['id'].append(0)
?
What I did before was this
Dic={}
Dic['name']=[]
Dic['name'].append('id')
but now I have to store some values of ID too and those are list of values.
You can use a defaultdict
to get what you want, for example:
from collections import defaultdict
d = {'name': defaultdict(list)}
d['name']['id'].append(0)
d['name']['id'].append(1)
d['name']['id'].append(2)
print(d)
>>> {'name': defaultdict(<class 'list'>, {'id': [0, 1, 2]})}
Dic = {}
Dic['name'] = {}
Dic['name']['id'] = []
Dic['name']['id'].append(0)
print(Dic)
This code segment gives the following output
{'name': {'id': [0]}}
I think this is the output you need
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.