0
How do i create a dictionary within a list? Ex:[{name: x,no:1},{name:y,no:2}]
I tried it but could not do it a=[ ] for i in range(3): a.append({}) print(a) d=dict() for i in range(3): d[i]=dict() d[i]['regno']=input("enter no:") d[i]['name']=input("enter name:") for i in range(3): a[i].append(d) print(a)
2 odpowiedzi
+ 6
# create a list with two dicts and automatically generated reg. numbers starting with 1:
a = [{'regno': i+1} for i in range(2)]
# result: [{'regno': 1}, {'regno': 2}]
# add/change entries manually (can be done via input() and/or a loop, too):
a[0]['name'] = 'John'
a[1]['name'] = 'Hubert'
a[0]['regno'] = 123
#result: [{'regno': 123, 'name': 'John'}, {'regno': 2, 'name': 'Hubert'}]
+ 4
a=[ ]
for i in range(3):
d={}
d['regno']=input("enter no:")
d['name']=input("enter name:")
a.append(d)
print(a)