简体   繁体   English

使用列表值遍历字典

[英]Iterating Through Dictionary with List Values

I am looking to iterate through a dictionary and create a new dictionary for each of the values within a list of the value shown below.我正在寻找遍历字典并为下面显示的值列表中的每个值创建一个新字典。 Each value will be either a single value or a list and each list would have the same length.每个值将是单个值或列表,并且每个列表的长度相同。 The first dictionary is the original one, and the others are the first two dictionaries I want to output.第一个字典是原始字典,其他是我要输出的前两个字典。 I ultimately want to just have those values, do something with them and then move onto the next dictionary output and so on.我最终只想拥有这些值,对它们做一些事情,然后转到下一个字典输出,依此类推。

dict = {'cost': [1, 3, 4, 8, 10],
        'address': '123 Fake St',
        'phone number': '123-456-7890',
        'item': ['apple', 'banana', 'strawberry', 'paper', 'pencil'],
        'name': 'John David'}

dict1 = {'cost': 1,
         'address': '123 Fake St',
         'phone number': '123-456-7890',
         'item': 'apple',
         'name': 'John David'}

dict2 = {'cost': 3,
         'address': '123 Fake St',
         'phone number': '123-456-7890',
         'item': 'banana',
         'name': 'John David'}

My attempt:我的尝试:

from collections import defaultdict 
custs = defaultdict(list)

for key, value in sorted(dict.iteritems()):
    custs[value].append(key)

I believe the following comprehension should do the trick:我相信以下理解应该可以解决问题:

d = {'cost': [1, 3, 4, 8, 10],
             'address': '123 Fake St',
             'phone number': '123-456-7890',
             'item': ['apple', 'banana', 'strawberry', 'paper', 'pencil'],
             'name': 'John David'}

res = [{**d, "cost": cost, "item": item} for cost, item in zip(d["cost"], d["item"])]

Which yields:产生:

{'cost': 1, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'apple', 'name': 'John David'}
{'cost': 3, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'banana', 'name': 'John David'}
{'cost': 4, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'strawberry', 'name': 'John David'}
{'cost': 8, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'paper', 'name': 'John David'}
{'cost': 10, 'address': '123 Fake St', 'phone number': '123-456-7890', 'item': 'pencil', 'name': 'John David'}

No comp version:没有comp版本:

for cost, item in zip(d["cost"], d["item"]):
    modified_d = {**d, "cost": cost, "item": item}
    do_stuff_with_modified_d(modified_d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM