4

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'}
Bernd Weiss
  • 927
  • 1
  • 14
  • 24
user2559679
  • 87
  • 1
  • 7

1 Answers1

5

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.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199