通过列表值的字典迭代
我希望通过词典进行迭代,并为下面显示的值列表中的每个值创建一个新的词典。每个值将是一个值或列表,每个列表的长度相同。第一个词典是原始词典,而其他字典是我要输出的前两个词典。我最终想拥有这些值,对它们做点事,然后移至下一个字典输出等等。
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'}
我的尝试:
from collections import defaultdict
custs = defaultdict(list)
for key, value in sorted(dict.iteritems()):
custs[value].append(key)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信以下理解应该可以解决问题:
哪个产生:
没有comp版本:
I believe the following comprehension should do the trick:
Which yields:
No comp version: