我完全改變了這個問題,使這個概念更容易。
我有一個列出的字典,我想列印出具有相同id鍵值的字典。
這是一個列出的字典:
testdata = [{"id": "test1",
"data":"book",
"type":"work"},
{"id": "test2",
"data":"cd",
"type":"school"},
{"id": "test1",
"data":"cd",
"type":"school"},
{"id": "test3",
"data":"book",
"type":"work"}]
示例問題 - 如何僅列印具有鍵值的test1字典id?
我可以通過說靜態地做到這一點:
for r in testdata:
if r["id"] == "test1":
print(r)
但是,如果我事先不知道 id 的名稱,我怎么能列印同樣的東西。如何動態查找具有相同 id 的鍵值并將它們列印在 forloop 中或附加到新串列中?
uj5u.com熱心網友回復:
ids = set((d['id'] for d in testdata))
for id_ in ids:
print ([data for data in testdata if data['id'] == id_])
#Output:
[{'id': 'test2', 'data': 'cd', 'type': 'school'}]
[{'id': 'test3', 'data': 'book', 'type': 'work'}]
[{'id': 'test1', 'data': 'book', 'type': 'work'}, {'id': 'test1', 'data': 'cd', 'type': 'school'}]
sort 和 groupby 也可以
from itertools import groupby
# create a func that gives the key to sort and group.
key_func = lambda d: d['id']
# First, Sort the list based on the needed field.
sorted_test_data = sorted(testdata, key=key_func)
# Next, simply group them by the field.
for key, group in groupby(sorted_test_data, key_func):
print(key " :", list(group))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456005.html
