如何遍历词典列表并创建新词典

时间:2020-08-27 20:37:57

标签: python dictionary

我正在尝试遍历下面的词典列表,其中“ dict”的==“ name”,价格(在这种情况下,其值为“ Variant OG”或“ Bad Axe”的值)放在一个单独的字典中。

{0, {s,i}}

基本上,所有相同的菜单项都在相同的字典中,但价格也有所不同

理想情况下,最终结果看起来像

[{'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1354, 'item': 'Giardiniera', 'Variant OG': 5.0},
 {'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1355, 'item': 'Sweet Peppers', 'Variant OG': 5.0},
 {'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1334, 'item': 'Hot Bar Serving Hardware', 'Variant OG': 5.0},
 {'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1354, 'item': 'Giardiniera', 'Bad Axe': 1.0},
 {'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1355, 'item': 'Sweet Peppers', 'Bad Axe': 1.0},
 {'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1334, 'item': 'Hot Bar Serving Hardware', 'Bad Axe': 1.0}]

2 个答案:

答案 0 :(得分:0)

如果先将list_of_dictionaries分为2个不同的列表,以便另一个包含所有“ Variant OG”,另一个包含所有“ Bad Axe”,则可能会更容易。

然后您可以轻松地遍历它们,例如

for variant in variant_OGs:
       for bad in bad_axes:
             if( variant['item']==bad['item']):
                   #put them into single dict

答案 1 :(得分:0)

似乎每个列表仅因Variant OGBad Axe而异,因此按itemitem_id进行排序,并使用itertools.groupby来迭代具有匹配的键将解决问题:

from itertools import groupby

lst = [{'menu':'','category':'Production Item','group':'','item_id':1354,'item':'Giardiniera','Variant OG':5.0},
       {'menu':'','category':'Production Item','group':'','item_id':1355,'item':'Sweet Peppers','Variant OG':5.0},
       {'menu':'','category':'Production Item','group':'','item_id':1334,'item':'Hot Bar Serving Hardware','Variant OG':5.0},
       {'menu':'','category':'Production Item','group':'','item_id':1354,'item':'Giardiniera','Bad Axe':1.0},
       {'menu':'','category':'Production Item','group':'','item_id':1355,'item':'Sweet Peppers','Bad Axe':1.0},
       {'menu':'','category':'Production Item','group':'','item_id':1334,'item':'Hot Bar Serving Hardware','Bad Axe':1.0}]


# groupby requires the container to be sorted by the key
sortkey = lambda x: x['item_id']
lst.sort(key=sortkey)

# "key" is the common key for the items
# "items" is an iterator of the common items
for key,items in groupby(lst,key=sortkey):
    # start with an empty dict for each common key
    dct = {}
    for item in items:
        # add all key/value pairs for each common key item to the dict
        dct.update(item)
    print(dct)

输出:

{'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1334, 'item': 'Hot Bar Serving Hardware', 'Variant OG': 5.0, 'Bad Axe': 1.0}
{'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1354, 'item': 'Giardiniera', 'Variant OG': 5.0, 'Bad Axe': 1.0}
{'menu': '', 'category': 'Production Item', 'group': '', 'item_id': 1355, 'item': 'Sweet Peppers', 'Variant OG': 5.0, 'Bad Axe': 1.0}
相关问题