首页 > 解决方案 > function to add dicts to a nested dict that give increasing keys

问题描述

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

标签: pythondictionarynested

解决方案


dict_of_dicts = dict(enumerate(list_of_dicts))

推荐阅读