Literal syntax
d = {} d = {'key': 'value'} # makes a shallow copy of otherdict d = {**otherdict} # also updates the shallow copy with the contents of the yetanotherdict. d = {**otherdict, **yetanotherdict} # dict comprehension d = {k:v for k,v in [('key', 'value',)]}
Dict.get method
One common pitfall when using dictionaries is to access a non-existent key. This typically results in a KeyError exception. One way to avoid key errors is to use the dict.get method, which allows you to specify a default value to return in the case of an absent key.
value = mydict.get(key, default_value)
Which returns mydict[key] if it exists, but otherwise returns default_value . Note that this doesn’t add key to mydict . So if you want to retain that key value pair, you should use mydict.setdefault(key, default_value) , which does store the key value pair.
mydict = {} print(mydict) # {} print(mydict.get("foo", "bar")) # bar print(mydict) # {} print(mydict.setdefault("foo", "bar")) # bar print(mydict) # {'foo': 'bar'}
Merging dictionaries
# Consider the following dictionaries: fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"} dog = {'name': "Clifford", 'hands': "paws", 'color': "red"} fishdog = {**fish, **dog} print(fishdog) # {'hands': 'paws', 'color': 'red', 'name': 'Clifford', 'special': 'gills'}
As this example demonstrates, duplicate keys map to their lattermost value (for example “Clifford” overrides “Nemo”).
Unpacking dictionaries using the ** operator
You can use the ** keyword argument unpacking operator to deliver the key -value pairs in a dictionary into a function’s arguments.
def parrot(voltage, state, action): print("This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.", end=' ') print("E's", state, "!") d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} parrot(**d) # This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
Dictionary Comprehensions
A dictionary comprehension is similar to a list comprehension except that it produces a dictionary object instead of a list.
F=dict((x, x * x) for x in (1, 2, 3, 4)) print(F) # Out: {1: 1, 2: 4, 3: 9, 4: 16}
As with a list comprehension, we can use a conditional statement inside the dict comprehension to produce only the dict elements meeting some criterion.
F={name: len(name) for name in ('Fcuk', 'The', 'Code') if len(name) > 3} print(F) # Out: {'Fcuk': 4, 'Code': 4}
Starting with a dictionary and using dictionary comprehension as a key-value pair filter
initial_dict = {'F': 1, 'C': 2} F={key: value for key, value in initial_dict.items() if key == 'F'} print(F) # Out: {'F': 1}
Switching key and value of dictionary (invert dictionary)
If you have a dict containing simple hashable values (duplicate values may have unexpected results):
my_dict = {1: 'a', 2: 'b', 3: 'c'}
you wanted to swap the keys and values you can take several approaches depending on your coding style:
'''Approaches''' ''' #1 '''swapped = {v: k for k, v in my_dict.items()} ''' #2 '''swapped = dict((v, k) for k, v in my_dict.iteritems()) ''' #3 '''swapped = dict(zip(my_dict.values(), my_dict)) ''' #4 '''swapped = dict(zip(my_dict.values(), my_dict.keys())) ''' #5 '''swapped = dict(map(reversed, my_dict.items())) print(swapped) '''All leads to same output ''' # Output: {a: 1, b: 2, c: 3}
If your dictionary is large, consider importing itertools and utilize izip or imap .
Merging Dictionaries
Combine dictionaries and optionally override old values with a nested dictionary comprehension.
dict1 = {'w': 1, 'x': 1} dict2 = {'x': 2, 'y': 2, 'z': 2} F={k: v for d in [dict1, dict2] for k, v in d.items()} print(F) # Out: {'w': 1, 'x': 2, 'y': 2, 'z': 2} #Python 3.x Version F={**dict1, **dict2} print(F) # Out: {'w': 1, 'x': 2, 'y': 2, 'z': 2}
Good V I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs and related information ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your client to communicate. Excellent task..
Wow! Thank you! I continuously wanted to write on my site something like that. Can I take a fragment of your post to my site?
Awsome info and right to the point. I don’t know if this is truly the best place to ask but do you guys have any thoughts on where to employ some professional writers? Thanks in advance 🙂
I like studying and I think this website got some truly utilitarian stuff on it! .
I’ve recently started a web site, the info you offer on this website has helped me greatly. Thanks for all of your time & work.
Thankyou for this post, I am a big big fan of this site would like to keep updated.
Just wanna tell that this is very useful, Thanks for taking your time to write this.
I like what you guys are up too. Such clever work and reporting! Keep up the superb works guys I¦ve incorporated you guys to my blogroll. I think it’ll improve the value of my web site 🙂
You got a very wonderful website, Glad I discovered it through yahoo.
Keep up the superb piece of work, I read few posts on this website and I believe that your blog is very interesting and holds sets of fantastic info .
Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?
I haven’t checked in here for a while since I thought it was getting boring, but the last few posts are great quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂
I just couldn’t depart your site prior to suggesting that I extremely enjoyed the standard information a person provide for your visitors? Is gonna be back often to check up on new posts
eaayg1