[英]Iterating Through Dictionary with List Values
我正在尋找遍歷字典並為下面顯示的值列表中的每個值創建一個新字典。 每個值將是單個值或列表,並且每個列表的長度相同。 第一個字典是原始字典,其他是我要輸出的前兩個字典。 我最終只想擁有這些值,對它們做一些事情,然后轉到下一個字典輸出,依此類推。
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)
我相信以下理解應該可以解決問題:
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"])]
產生:
{'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'}
沒有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.