简体   繁体   English

字典理解,同时检查键是否已存在?

[英]Dictionary comprehension whilst checking if key already exists?

I know you can check if a key exists using: 我知道您可以使用以下方法检查密钥是否存在:

if key in mydict:
    ...

but I wish to somehow use this in a dictionary comprehension as I construct the dictionary. 但是我希望在构建字典时以某种方式在字典理解中使用它。

For example: 例如:

mylist = [('a', 0.01), ('b', 0.02), ('c', 0.03), ('a', 0.04)]
mydict = {item[0]: item[1] for item in mylist if item[0] not in mydict else blah blah}

What's the best way to achieve this? 实现此目标的最佳方法是什么?

I need the else part also. 我还需要其他部分。

Edit: For clarification. 编辑:为澄清。 In my case I actually need the sum of item[1] values for all items with a given item[0] value. 就我而言,我实际上需要具有给定item [0]值的所有项目的item [1]值总和。

Python dict is unordered structure with unique keys. Python dict是具有唯一键的无序结构。 As you need values of firstly encountered keys - iterate input list in reversed order: 由于您需要首先遇到的键的值-以相反的顺序迭代输入列表:

mylist = [('a', 0.01), ('b', 0.02), ('c', 0.03), ('a', 0.04)]
mydict = {t[0]:t[1] for t in mylist[::-1]}

print(mydict)

The output: 输出:

{'a': 0.01, 'c': 0.03, 'b': 0.02}

With dictionary comprehension: 通过字典理解:

mylist = [('a', 0.01), ('b', 0.02), ('c', 0.03), ('a', 0.04)]
mydict = {key:value for key, value in mylist[::-1]}
print(mydict)

Output: 输出:

{'a': 0.01, 'c': 0.03, 'b': 0.02}

Without dictionary comprehension: 没有字典理解:

mydict = {}
for key, value in mylist:
    if key not in mydict:
        mydict[key] = value
    else:
        # You asked for the else part. Do whatever here.   
print(d)

Output: 输出:

{'a': 0.01, 'c': 0.03, 'b': 0.02}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM