Showing posts with label dictionary. Show all posts
Showing posts with label dictionary. Show all posts

Thursday, April 1, 2010

Python: Swapping the keys and values of a dictionary

A function to swap the keys and immutable values of a dictionary.
def swap_dict(a_dict):
    return {val:key for key, val in a_dict.items()}
Example of usage:
>>> print(swap_dict({1: 'a', 2: 'b', 3: 'c'}))
{'a': 1, 'c': 3, 'b': 2}

Thursday, May 21, 2009

How to store functions in a dictionary in Python

This example uses a dictionary to store functions.

To call the function, use the dictionary key.
>>> f = {'plus_all':sum, 'find_max':max}
>>> f['find_max'](1,4,5,3,2,6)
6
>>> f['plus_all'](range(10))
45

Saturday, May 16, 2009

How to sum the values of a Python dictionary

Suppose that we have a Python dictionary,
x = {'a': 3, 'b': 2, 'c':7}

and, we want to add the values i.e. 3 + 2 + 7 = 12.

Here are the three ways to add the values.


Using list comprehension

>>> x = {'a': 3, 'b': 2, 'c':7}
>>> sum([i for i in x.values()])
12

Using for loop I

>>> x = {'a': 34, 'b': 2, 'c':7}
>>> total = 0
>>> for i in x.values():
total += i

Using for loop II

>>> x = {'a': 34, 'b': 2, 'c':7}
>>> total = 0
>>> for key in x.keys():
total += x[key]

Thursday, February 19, 2009

How to convert two Python lists into a dictionary

To convert two Python lists into a dictionary. First, pair the two list with the zip() function, as key-value pairs. The last step is to use the dict() constructor to build a dictionary directly from the key-value pairs.
>>> x = ['a', 'b', 'c']
>>> y = [1 ,2 ,3]
>>> dict(zip(x,y))
{'a': 1, 'c': 3, 'b': 2}

We can also zip the two lists together, as list of tuples, and use the dict() constructor for the iterator of that list.
>>> x = ['a', 'b', 'c']
>>> y = [1, 2, 3]
>>> dict(iter(list(zip(x, y))))
{'a': 1, 'c': 3, 'b': 2}

Wednesday, August 27, 2008

Find max or min in Python dictionary

Suppose that mydict is a dictionary defined by
mydict = {'a': 2, 'c': 5, 'b': 1, 'd': 4}
How to find the key for the max or min value in the items?

Applying
max(mydict)
would produce 'd'. This is wrong. The answer should be 'c'.

Doing it this way, the Python try to find the max in the key part. In this case, 'd' is the max, in alphabetical order.

The correct way is,
max(mydict, key = lambda x: mydict.get(x) )
Similarly, to find the min,
min(mydict, key = lambda x: mydict.get(x) )

Tuesday, August 26, 2008

Sort Python dictionary

Suppose that mydict is a dictionary defined by
mydict = {'a': 2, 'c': 5, 'b': 1, 'd': 4}
Remember that dictionary has no function sort, since it is unordered, not like a list, or tuple.

However, the key function, introduced in version 2.4, is helpful in sorting a dictionary.

To sort by items, and return the keys and items,
sorted( mydict.items(), key=lambda x: x[1] )
output:
[('b', 1), ('a', 2), ('d', 4), ('c', 5)]
To return only the keys, sorted by the items,
sorted( mydict.keys(), key=lambda x: mydict[x] )
output:
['b', 'a', 'd', 'c']
Note that, adding reverse=True at the end of the sorted function would produce a decending order list.
sorted( mydict.items(), key=lambda x: x[1] )
output:
[('c', 5), ('d', 4), ('a', 2), ('b', 1)]
Happy sorting.