Top dictionary Questions

List of Tags

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place.

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print z
>>> x
{'a': 1, 'b': 10, 'c': 11}

So I want that final merged dict in z, not x. How can I do this?

Answered By: Thomas Vander Stichele ( 422)

In your case, what you can do is:

z = dict(x.items() + y.items())

This will, as you want it, put the final dict in z, and make the value for b be properly overridden by the second (y) dict's value:

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 11, 'b': 10}

If you use Python 3, it is only a little more complicated. To create z:

>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{'a': 1, 'c': 11, 'b': 10}
dark fader

I have a dictionary of values read from 2 fields in a database: a string field and a numeric field. The string field is unique so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

Note: I have read this post and probably could change my code to have a list of dictionaries but since I do not really need a list of dictionaries I wanted to know if there a simpler solution.

Answered By: Devin Jeanpierre ( 485)

It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples. For instance,

import operator
x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))

sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

Jake Stewart

I've seen a few different ways to iterate over a Dictionary in C#. Is there a standard way?

Answered By: Pablo Fernandez ( 391)
foreach(KeyValuePair<String,String> entry in MyDic)
    // do something with entry.Value or entry.Key

Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method...

Answered By: Paolo Bergantino ( 299)
>>> d = {'key':'value'}
>>> print d
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print d
{'mynewkey': 'mynewvalue', 'key': 'value'}

I got a list of dictionaries and want that to be sorted by a value of that dictionary.


[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]

sorted by name, should become

[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
Answered By: Mario Fernandez ( 286)

It may look cleaner using a key instead a cmp:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

or as J.F.Sebastian and others suggested,

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 

I like the python list comprehension operator (or idiom, or whatever it is).

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}  # doesn't work :(
Answered By: fortran ( 291)

In Python 2.6 (or earlier), use the dict constructor:

d = dict((key, value) for (key, value) in sequence)

In Python 2.7+ or 3, you can just use the dict comprehension syntax directly:

d = {key: value for (key, value) in sequence}