插入python字典 [英] inserting into python dictionary

查看:47
本文介绍了插入python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python字典的默认行为是在字典中创建新密钥(如果该密钥尚不存在).例如:

The default behavior for python dictionary is to create a new key in the dictionary if that key does not already exist. For example:

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

对于大多数用途来说,这一切都很好,但是如果密钥中没有键,我希望python不执行任何操作,该怎么办?在我的情况下:

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. In my situation:

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

换句话说,我不希望异常中的某些不正确元素破坏我的主列表.这是否就这么简单? FEELS 之类的,我应该能够在for循环内的一行中执行此操作(即,无需显式检查x是否是主列表的键)

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 (i.e., without explicitly checking that x is a key of masterlist)

更新:对我来说,我的问题是询问列表和字典之间缺乏相似之处.例如:

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

使用子类化答案,您可以修改字典(也许是"safe_dict"或"explicit_dict"进行类似的操作:

with the subclassing answer, you could modify the dictionary (maybe "safe_dict" or "explicit_dict" to do something similar:

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

推荐答案

您可以继承 dict 类,覆盖它的 __ setitem __ 来检查键的存在(或执行猴子只修补一个实例也是如此).

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).

示例类别:

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.

这篇关于插入python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆