user2559679
user2559679

Reputation: 89

Making a dictionary from a list of strings (creating keys from the elements of the list)

I am using Python 3.3. I was curious how I can make a dictionary out of a list:

Lets say my list containing strings is

list = ['a;alex', 'a;allison', 'b;beta', 'b;barney', 'd;doda', 'd;dolly']

I want to make it into a dictionary like this:

new_dict = { {'a': {'alex','allison'}}
             {'b': {'beta','barney'}}
             {'d': {'doda', 'dolly'}} }

so later I can print it out like this:

Names to be organized and printed:
   a -> {'alex', 'allison'}
   b -> {'beta', 'barney'}
   d -> {'doda', 'dolly'}

How would I approach this? Many thanks in advance!

-UPDATE-

So far I have this:

reached_nodes = {}

for i in list:
    index = list.index(i)
    reached_nodes.update({list[index][0]: list[index]})

But it outputs into the console as:

{'a': 'a;allison', 'b': 'b;barney', 'd': 'd;dolly'}

Upvotes: 4

Views: 337

Answers (1)

Nafiul Islam
Nafiul Islam

Reputation: 82460

Well, you can use defaultdict:

>>> from collections import defaultdict
>>> l = ['a;alex', 'a;allison', 'b;beta', 'b;barney', 'd;doda', 'd;dolly']
>>> var = defaultdict(list)
>>> for it in l:
    a, b = it.split(';')
    var[a].append(b)
>>> var
defaultdict(<type 'list'>, {'a': ['alex', 'allison'], 'b': ['beta', 'barney'], 'd': ['doda', 'dolly']})
>>> for key, item in var.items():
...     print "{} -> {{{}}}".format(key, item)
...     
a -> {['alex', 'allison']}
b -> {['beta', 'barney']}
d -> {['doda', 'dolly']}

If you would like to get rid of the [], then try the following:

>>> for key, value in var.items():
...     print "{} -> {{{}}}".format(key, ", ".join(value))
a -> {alex, allison}
b -> {beta, barney}
d -> {doda, dolly}

If you would like the values in a set and not a list, then just do the following:

var = defaultdict(set)

And use .add instead of .append.

Upvotes: 5

Related Questions