Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting into python dictionary

Tags:

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 (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 

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 
like image 901
Ramy Avatar asked Jun 23 '11 15:06

Ramy


People also ask

Can I add to dictionary Python?

Python add to Dictionary using “=” assignment operator We do not have any specific Python way to update a dictionary. If you want to add a new key to the dictionary, then you can use the assignment operator with the dictionary key. This is pretty much the same as assigning a new value to the dictionary.

How do I add an item to an empty dictionary in Python?

How to Add New Items to A Dictionary in Python. To add a key-value pair to a dictionary, use square bracket notation. First, specify the name of the dictionary. Then, in square brackets, create a key and assign it a value.

How do you add a string to a dictionary?

You can't . append() to a string because a string is not mutable. If you want your dictionary value to be able to contain multiple items, it should be a container type such as a list. The easiest way to do this is just to add the single item as a list in the first place.


2 Answers

You could use .update:

masterlist.update((x, False) for x in exceptions if masterlist.has_key(x)) 
like image 72
Felix Kling Avatar answered Jan 02 '23 23:01

Felix Kling


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.

like image 31
3 revs Avatar answered Jan 02 '23 23:01

3 revs