簡體   English   中英

比較python中的兩個字典以獲得相似鍵的最大值

[英]comparing two dict in python to get the maximum value for similar key

我有以下兩個命令:

a={"test1":90,  "test2":45,  "test3":67,  "test4":74}
b={"test1":32,  "test2":45,  "test3":82,  "test4":100}

如何為相同的鍵提取最大值以獲取新的字典,如下所示:

c={"test1":90,  "test2":45,  "test3":82,  "test4":100}

你可以這樣嘗試

>>> a={"test1":90, "test2":45, "test3":67, "test4":74} 
>>> b={"test1":32, "test2":45, "test3":82, "test4":100}
>>> c = { key:max(value,b[key]) for key, value in a.iteritems() }
>>> c
{'test1': 90, 'test3': 82, 'test2': 45, 'test4': 100}

嘗試這個:

>>> a={"test1":90, "test2":45, "test3":67, "test4":74} 
>>> b={"test1":32, "test2":45, "test3":82, "test4":100}
>>> c={ k:max(a[k],b[k]) for k in a if b.get(k,'')}
{'test1': 90, 'test3': 82, 'test2': 45, 'test4': 100}

不是最好的,但仍然是一個變體:

from itertools import chain

a = {'test1':90, 'test2': 45, 'test3': 67, 'test4': 74}
b = {'test1':32, 'test2': 45, 'test3': 82, 'test4': 100, 'test5': 1}

c = dict(sorted(chain(a.items(), b.items()), key=lambda t: t[1]))
assert c == {'test1': 90, 'test2': 45, 'test3': 82, 'test4': 100, 'test5': 1}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM