简体   繁体   中英

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

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:

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

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.

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.

For long lists try to use the & operator with set() function embraced with () :

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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