Creating a dictionary from a list of strings (creating keys from list items)

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

Lets say my list containing strings

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

I want to do this in a dictionary as follows:

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

so I can print it as follows:

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

How do I approach this? Thank you very much 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 is displayed in the console as:

{'a': 'a;allison', 'b': 'b;barney', 'd': 'd;dolly'}
+4
source share
1 answer

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 want to get rid of [], 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 need values ​​in set, not a list, just follow these steps:

var = defaultdict(set)

.add .append.

+5

All Articles