简体   繁体   English

从字符串列表中创建字典(从列表元素创建键)

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

I am using Python 3.3. 我使用的是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- -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'}

Well, you can use defaultdict : 好吧,你可以使用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: 如果您想要set的值而不是list ,那么只需执行以下操作:

var = defaultdict(set)

And use .add instead of .append . 并使用.add而不是.append

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM