Split a dictionary into two lists or vice versa in Python

Posted in python

Sometimes a dictionary is nice for keeping things simple. You can directly access any value by looking at the key. But perhaps you need to split the dictionary up into two lists. Or go the other way; turn two related lists into a key-value dictionary.

banana-split

Dictionary to Lists

Given a dictionary:

d = {}
d[a] = "1"
d[b] = "2"
d[c] = "3"

Split it into two lists:

alpha = []
numeric = []

Method #1

for key, value in .items():
    alpha.append(key)
    numeric.append(value)

Method #2

for key in d:
    alpha.append(key)
    numeric.append(d[key])

Lists to Dictionary

Going back to a dictionary is even easier.

newdict = dict(zip(alpha, numeric)
Posted by admica   @   16 April 2010
Tags : , , , , ,

Related Posts

Like this post? Share it!

Digg Twitter StumbleUpon Delicious Technorati Facebook RSS

2 Comments

Comments
May 6, 2010
1:15 pm

Thanks for this.

For Dictionary to Lists, How about:
alpha, numeric = zip(*d.iteritems())

Dec 1, 2010
12:50 am
#2 soatnheu :

alpha = d.keys()
numeric = d.values()

No need for loops, man.

Leave a Comment

Name

Email

Website

Previous Post
« Show methods for any object in Python
Next Post
Share keyboard and mouse between multiple Windows, Linux, and Mac computers with or without a KVM switch »
Powered by Wordpress   |   Lunated designed by ZenVerse