在字典中给它的键赋值

2024-04-26 10:49:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试从两个列表中创建一个字典,这两个列表基于它们的索引相互关联,即list1[I]->;list2[I]。可以看出,keys列表包含重复的值,我希望将较低的值分配给相应的键(例如,键9的值1和9,但我需要较低的值)

keys = [9, 9, 8, 10, 10]
values = [1, 9, 1, 6, 1]
dict = {10:1, 9:1, 8:1} #end result

注意:我正在使用字典,因为我正试图利用这样一个事实,即不能有重复的键-如果有更好的数据结构的建议,请让我知道


Tags: gt利用数据结构列表字典resultkeys建议
2条回答

只需遍历键和值,并使用min指定最小值:

>>> keys = [9, 9, 8, 10, 10]
>>> values = [1, 9, 1, 6, 1]
>>> inf = float('inf')
>>> result = {}
>>> for k,v in zip(keys, values):
...     result[k] = min(v, result.get(k, inf))
...
>>> result
{9: 1, 8: 1, 10: 1}

注意,我利用了float(inf)总是大于其他数字的事实。你知道吗

或者,只需检查字典中的值:

>>> result = {}
>>> for k, v in zip(keys, values):
...     if k in result:
...         result[k] = min(v, result[k])
...     else:
...         result[k] = v
...
>>> result
{9: 1, 8: 1, 10: 1}
keys = [9, 9, 8, 10, 10]
values = [1, 9, 1, 6, 1]

# By sorting in descending order based upon values, 
# smaller later values overwrite larger earlier 
# values in dictionary comprehension
result = dict(sorted(zip(keys, values), key=lambda x: x[1], reverse = True))

print(result) # => {9: 1, 10: 1, 8: 1}

相关问题 更多 >