0

Lets say that I have an empty dictionary. How would I go about writing a function that would add other dictionaries to the empty one, giving it a key that would increase for every new dictionary added?

So it would result in something like:

{0: {'name': 'pork', 'cals': 100, 'pro': 10, 'sugar': 1},
 1: {'name': 'chicken', 'cals': 190, 'pro': 19, 'sugar': 19},
 2: {'name': 'beef', 'cals': 160, 'pro': 12, 'sugar': 2}}
4

3 回答 3

1
dict_of_dicts = dict(enumerate(list_of_dicts))
于 2021-08-26T22:31:40.627 回答
1

您只需创建要添加的字典列表,然后使用简单的 for 循环将它们添加到字典中:

result = {}
ex1 = {'name': 'pork', 'cals': 100, 'pro': 10, 'sugar': 1}
ex2 = {'name': 'chicken', 'cals': 190, 'pro': 19, 'sugar': 19}
ex3 = {'name': 'beef', 'cals': 160, 'pro': 12, 'sugar': 2}
listDict = [ex1,ex2,ex3]

for i in range(len(listDict)):
  result[i] = listDict[i]
print(result)

输出:

{0: {'name': 'pork', 'cals': 100, 'pro': 10, 'sugar': 1}, 1: {'name': 'chicken', 'cals': 190, 'pro': 19, 'sugar': 19}, 2: {'name': 'beef', 'cals': 160, 'pro': 12, 'sugar': 2}}
于 2021-08-26T22:37:43.470 回答
0

这是可以帮助您的代码:

def add_dict(d1, out_dict):
    new_key = len(out_dict.keys())
    out_dict[new_key] = d1
    
ex1 = {'name': 'pork', 'cals': 100, 'pro': 10, 'sugar': 1}
ex2 = {'name': 'chicken', 'cals': 190, 'pro': 19, 'sugar': 19}
ex3 = {'name': 'beef', 'cals': 160, 'pro': 12, 'sugar': 2}
listDict = [ex1,ex2,ex3]

out = {}
for dict1 in listDict:
    add_dict(dict1, out)
    
print (out)
于 2021-08-27T06:16:04.317 回答