我有一個字典串列:
foo = [{'name':'John Doe', 'customer':'a'},
{'name':'John Doe', 'customer':'b'},
{'name':'Jenny Wang', 'customer':'c'},
{'name':'Mary Rich', 'customer': None}
]
有沒有辦法獲取第一個鍵的值并將其設定為新鍵,新字典的值是第二個鍵的值。
預期結果:
{'John Doe':['a', 'b'], 'Jenny Wang':['c'], 'Mary Rich':[]}
uj5u.com熱心網友回復:
你可以使用dict.setdefault. 這個想法是將一個空串列初始化為每個鍵的值。然后檢查一個名稱是否已經作為鍵存在并將非 None 值附加到它(is not None檢查是必要的,因為如果它被遺漏,其他不真實的值(例如 False)可能會被遺漏;感謝@Grismar)
out = {}
for d in foo:
out.setdefault(d['name'], [])
if d['customer'] is not None:
out[d['name']].append(d['customer'])
輸出:
{'John Doe': ['a', 'b'], 'Jenny Wang': ['c'], 'Mary Rich': []}
uj5u.com熱心網友回復:
@enke 答案清晰明了,但添加我的答案以防它以某種方式有所幫助。
一些不同的實作可能是:
foo = [{'name':'John Doe', 'customer':'a'},
{'name':'John Doe', 'customer':'b'},
{'name':'Jenny Wang', 'customer':'c'},
{'name':'Mary Rich', 'customer': None}
]
new_dict = dict()
for fo in foo:
if fo['name'] not in new_dict:
if fo['customer'] is None:
new_dict[fo['name']] = []
else:
new_dict[fo['name']] = [fo['customer']]
else:
if fo['customer'] is None:
new_dict[fo['name']].append()
else:
new_dict[fo['name']].append(fo['customer'])
print(new_dict)
輸出
{'John Doe': ['a', 'b'], 'Jenny Wang': ['c'], 'Mary Rich': []}
uj5u.com熱心網友回復:
itertools中有一個名為groupby的函式。它根據您提供的標準拆分您的輸入串列。然后它可以看起來像那樣。
from itertools import groupby
foo = [{'name':'John Doe', 'customer':'a'},
{'name':'John Doe', 'customer':'b'},
{'name':'Jenny Wang', 'customer':'c'},
{'name':'Mary Rich', 'customer': None}
]
def func_group(item):
return item['name']
def main():
for key, value in groupby(foo, func_group):
print(key)
print(list(value))
這不會完全導致您的預期輸出,但會接近:
John Doe
[{'name': 'John Doe', 'customer': 'a'}, {'name': 'John Doe', 'customer': 'b'}]
Jenny Wang
[{'name': 'Jenny Wang', 'customer': 'c'}]
Mary Rich
[{'name': 'Mary Rich', 'customer': None}]
(您現在可以應用兩次并獲得所需的輸出。我只是在這里展示了原理 :-))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430277.html
