我对如何将列表转换成字典进行了很多搜索,找到了解决方案,但是没有一个给出解决方案。
我有一个列表
LIST = {"x-y", "w-z","a-b"}
现在我想将其转换成应该像
的字典DICT = {'x':'y', 'w':'z', 'a':'b'}
答案 0 :(得分:2)
input = {"x-y", "w-z","a-b"}
output = dict(x.split('-', 1) for x in input)
答案 1 :(得分:1)
d = {x.split('-')[0]: x.split('-')[1] for x in LIST}
答案 2 :(得分:0)
使用dict
例如:
l = {"x-y", "w-z","a-b"}
print( dict([i.split("-") for i in l]) )
输出:
{'a': 'b', 'x': 'y', 'w': 'z'}
注意:l
是set
而不是列表
答案 3 :(得分:0)
遇到此类问题时,最好仔细考虑一些事情。
什么是字典?
字典在概念上是键值存储,意味着字典中的每个 元素都是一对(key, value)
。我们可以使用d[key] = value
为字典分配值,也可以使用d[key]
检索值。
现在我们知道如何将值放入字典中。
输入数据的格式是什么? 和我需要做什么来转换我的输入数据?
或者输入格式为<key>-<value>
,这意味着我们可以使用split
来
提取键和值。
>>> "x-y".split("-")
['x', 'y']
这使我们能够做到这一点:
DICT = {}
for element in LIST:
parts = element.split("-")
if len(parts) != 2:
# handle this case? (see below)
...
(key, value) = (parts[0], parts[1])
DICT[key] = value
如何处理错误?
我的输入格式可以包含x-y-a
吗?这是什么?这是(x-y,a)
还是(x,y-a)
?还是非法?我该如何处理-
?如果其中没有-
,该如何处理?即
>>> dict(x.split('-', 1) for x in ["a"])
如果使用这种方法,将引发您可能要处理的异常:
>>> dict(x.split('-', 1) for x in ["a"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
例如, dict(x.split('-', 1) for x in
仅适用于格式正确的输入。
还有其他构建词典的方法吗?
通读文档,您会发现dict
包含2个元组的列表。这意味着您可以执行以下操作:
>>> dict([('a','b'),('c','d')])
{'a': 'b', 'c': 'd'}
答案 4 :(得分:0)
d = {} //simple dictionary declaration
for i in LIST: // for loop to iterate and access each element of LIST
d[i[0]] = i[2] // this will use 1st letter of each word as key and 3rd letter as value of dictionary