Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串列表创建字典(从列表元素创建键)_Python_List_Dictionary - Fatal编程技术网

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

Python 从字符串列表创建字典(从列表元素创建键),python,list,dictionary,Python,List,Dictionary,我正在使用Python 3.3。我很好奇如何从列表中编出一本词典: 假设我的包含字符串的列表是 list = ['a;alex', 'a;allison', 'b;beta', 'b;barney', 'd;doda', 'd;dolly'] 我想把它写成这样一本字典: new_dict = { {'a': {'alex','allison'}} {'b': {'beta','barney'}} {'d': {'doda', 'dolly'}

我正在使用Python 3.3。我很好奇如何从列表中编出一本词典:

假设我的包含字符串的列表是

list = ['a;alex', 'a;allison', 'b;beta', 'b;barney', 'd;doda', 'd;dolly']
我想把它写成这样一本字典:

new_dict = { {'a': {'alex','allison'}}
             {'b': {'beta','barney'}}
             {'d': {'doda', 'dolly'}} }
Names to be organized and printed:
   a -> {'alex', 'allison'}
   b -> {'beta', 'barney'}
   d -> {'doda', 'dolly'}
以后我可以这样打印出来:

new_dict = { {'a': {'alex','allison'}}
             {'b': {'beta','barney'}}
             {'d': {'doda', 'dolly'}} }
Names to be organized and printed:
   a -> {'alex', 'allison'}
   b -> {'beta', 'barney'}
   d -> {'doda', 'dolly'}
我将如何处理这个问题?非常感谢

-更新-

到目前为止,我有:

reached_nodes = {}

for i in list:
    index = list.index(i)
    reached_nodes.update({list[index][0]: list[index]})
但它会输出到控制台,如下所示:

{'a': 'a;allison', 'b': 'b;barney', 'd': 'd;dolly'}
那么,你可以使用:

如果您希望设置
中的值,而不是
列表中的值,则只需执行以下操作:

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

使用
.add
而不是
.append

到目前为止,你试过什么了吗?如果是,你能提供你的代码吗?你到底需要什么?从字符串中提取键值是否有问题?在dict中插入条目?几乎是重复的:@Ffisegydd,可以很容易地安排。@Ffisegydd完成。希望这就足够了,但我认为OP没有提到他/她的确切需求,所以我选择了列表而不是设置。当然,+1:D出于某种原因,OP确实需要设置。谢谢!它起作用了。但是有没有可能强制按字母顺序打印出来呢?只需浏览一下目录并对每个列表进行排序。