Showing posts with label dict(). Show all posts
Showing posts with label dict(). Show all posts

Wednesday, August 19, 2009

Python: How to convert a dictionary into a list of key-value

Using the list() function, we can convert a dictionary into a list of key-value tuple.
>>> x = {'a':1, 'b':2}
>>> x
{'a': 1, 'b': 2}
>>> y = list(x.items())
>>> y
[('a', 1), ('b', 2)
To convert back into dictionary, use the dict() function.
>>> z = dict(y)
>>> z
{'a': 1, 'b': 2}

Tuesday, February 24, 2009

How to sort Python dictionary

To sort a Python dictionary, and append the keys into a list.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> sorted(x, key=x.get)
['c', 'a', 'b']

To sort a Python dictionary, and append tuples of the key and value into a list.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]

To sort a Python dictionary, and append the keys into a tuple, and the values into a tuple.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> the_keys, the_vals = zip(*[(the_key, x[the_key])
for the_key in sorted(x, key=x.get)])
>>> the_keys
('c', 'a', 'b')
>>> the_vals
(1, 2, 3)

The results from the above examples are in ascending order. To sort in descending order, attach reverse=True at the end of the sorted() function.
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> sorted(x, key=x.get, reverse=True)
['b', 'a', 'c']

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}