[英]Intersect a list of dicts based on a common key
假設我有兩個字典:
dates = [{'created':'2010-12-01'},{'created':'2010-12-02'},....]
elts = [{'created':'2010-12-01', 'key1':'val1', 'key2':'val2'}, {'created':'2010-12-05','key1':'val1'}]
日期列表是一堆連續的日期。
elts列表可以是1到len(dates)之間的任意值,而我想做的基本上是填充elts,以便無論是否有其他鍵,它都有一個日期的字典。
這是我天真的解決方案:
for d in dates:
for e in elts:
if d['created'] == e['created']:
d.update(dict(key1=e['key1']))
因此,我將得到一個最終array d
,每個dict
中都帶有所有日期,但是可能/可能沒有其他鍵/值。
什么是好的“ pythonic”解決方案?
我認為您的問題有些懸而未決,因為您的解決方案似乎並未真正解決您的問題,但是如果您想在elts
為尚未出現在elts
中的dates
中的每個日期創建一個條目,則可以使用此方法:
all_dates = set(e['created'] for e in dates) # gets a list of all dates that exist in `dates`
elts_dates = set(e['created'] for e in elts) # same for elts
missing_dates = all_dates - elts_dates
for entry in missing_dates:
elts.append(dict(created=entry))
這是一個http://codepad.org片段,顯示了該片段的效果: http : //codepad.org/n4NbjvPM
編輯:不同的解決方案:
設定一組您已經擁有的日期:
dates_in_elts = set(e['created'] for e in elts)
for d in dates:
if d['created'] not in dates_in_elts:
e.append(d)
這只會對每個列表進行一次迭代,而不是對日期中的每個日期進行迭代。
我可能會改用那些列表字典。
dates_d = dict([(x['created'], x) for x in dates])
elts_d = dict([(x['created'], x) for x in elts])
dates_d.update(elts_d)
如果您隨后需要將其重新排列為字典列表,則可以輕松做到這一點:
dates = [dates_d[x] for x in sorted(dates_d)]
但是,如果您除了合並以外沒有做其他事情,您的解決方案可能更容易閱讀。 但我懷疑,在這種情況下,字典列表並不是一種非常方便的數據格式。
也許我讀錯了,但在我看來,代碼的最終結果是,對於elts中的每個字典,您真的只想從elts復制該字典以覆蓋日期中的相應字典。
>>> for d in dates:
... for e in elts:
... if d['created'] == e['created']:
... d.update(e)
那時,正是日期字典反映了我認為您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.