简体   繁体   English

插入python字典

[英]inserting into python dictionary

The default behavior for python dictionary is to create a new key in the dictionary if that key does not already exist. python字典的默认行为是在字典中创建新密钥(如果该密钥尚不存在)。 For example: 例如:

d = {}
d['did not exist before'] = 'now it does'

this is all well and good for most purposes, but what if I'd like python to do nothing if the key isn't already in the dictionary. 对于大多数用途来说,这一切都很好,但是如果键不在字典中,我希望python什么也不做。 In my situation: 在我的情况下:

for x in exceptions:
    if masterlist.has_key(x):
        masterlist[x] = False

in other words, i don't want some incorrect elements in exceptions to corrupt my masterlist. 换句话说,我不希望在例外中有一些不正确的元素来破坏我的主列表。 Is this as simple as it gets? 这样简单吗? it FEELS like I should be able to do this in one line inside the for loop (ie, without explicitly checking that x is a key of masterlist) 感觉就像我应该能够在for循环中的一行中做到这一点(即,没有明确地检查x是主列表的关键)

UPDATE: To me, my question is asking about the lack of a parallel between a list and a dict. 更新:对我来说,我的问题是询问列表和字典之间缺乏平行。 For example: 例如:

l = []
l[0] = 2 #fails
l.append(2) #works

with the subclassing answer, you could modify the dictionary (maybe "safe_dict" or "explicit_dict" to do something similar: 使用子类化答案,您可以修改字典(可能是“safe_dict”或“explicit_dict”来执行类似的操作:

d = {}
d['a'] = '1' #would fail in my world
d.insert('a','1') #what my world is missing

你可以使用.update

masterlist.update((x, False) for x in exceptions if masterlist.has_key(x))

You can inherit a dict class, override it's __setitem__ to check for existance of key (or do the same with monkey-patching only one instance). 你可以继承一个dict类,覆盖它的__setitem__来检查key的存在(或者只修复一个实例的猴子修复)。

Sample class: 样本类:

class a(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        dict.__setitem__(self, 'a', 'b')

    def __setitem__(self, key, value):
        if self.has_key(key):
          dict.__setitem__(self, key, value)

a = a()
print a['a'] # prints 'b'
a['c'] = 'd'
# print a['c'] - would fail
a['a'] = 'e'
print a['a'] # prints 'e'

You could also use some function to make setting values without checking for existence simpler. 您还可以使用某些函数来设置值,而无需检查是否存在更简单。
However, I though it would be shorter... Don't use it unless you need it in many places. 但是,我会更短......除非你在很多地方需要它,否则不要使用它。

You can also use in instead of has_key , which is a little nicer. 你也可以使用in而不是has_key ,这是一个更好的。

for x in exceptions:
    if x in masterlist:
        masterlist[x] = False

But I don't see the issue with having an if statement for this purpose. 但是我没有看到为此目的而使用if语句的问题。

For long lists try to use the & operator with set() function embraced with () : 对于长列表尝试使用&操作与set()函数接受与()

    for x in (set(exceptions) & set(masterlist)):
        masterlist[x] = False
        #or masterlist[x] = exceptions[x]

It'll improve the reading and the iterations at the same time by reading the masterlist's keys only once. 通过只读一次masterlist的键,它将同时改善读数和迭代次数。

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

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