[英]From a list of strings to a dictionary
Say I have a list holding the following items:假设我有一个包含以下项目的列表:
["FOO x 2", "BAR x 11", "PERC"]
I would like to convert this list to a dictionary with the following result:我想将此列表转换为字典,结果如下:
{"FOO": 2, "BAR": 11, "PERC": 1}
Any ideas on how to approach this problem?关于如何解决这个问题的任何想法?
You could go with supplying a comprehension to dict
:您可以提供对
dict
的理解:
l = ["FOO x 2", "BAR x 11", "PERC"]
d = dict((tuple(map(str.strip, i.split('x'))) if 'x' in i else (i, 1) for i in l))
print(d)
{'BAR': '11', 'FOO': '2', 'PERC': 1}
Though a for-loop
definitely beats it in readability:尽管
for-loop
在可读性方面肯定胜过它:
d = {}
for i in l:
if 'x' in i:
k, v = map(str.strip, i.split('x'))
d[k] = v
else:
d[i] = 1
A one-liner:单线:
d = {x[0].strip(): int(x[1]) for x in ((elm + 'x 1').split('x') for elm in lst)}
print(d)
Output:输出:
{'BAR': 11, 'FOO': 2, 'PERC': 1}
Alternatively, you can take advantage of the new unpacking feature with *
in Python 3:或者,您可以利用 Python 3 中带有
*
的新解包功能:
lst = ["FOO x 2", "BAR x 11", "PERC"]
res = {}
for x in lst:
name, *count = (x + 'x 1').split('x')
res[name.strip()] = int(count[0])
print(res)
Output: {'BAR': 11, 'FOO': 2, 'PERC': 1}输出:{'BAR':11,'FOO':2,'PERC':1}
Below snippet code can do what you want to do下面的代码片段可以做你想做的事
lst = ["FOO x 2", "BAR x 11", "PERC"];
lst1 = list()
for elem in lst:
splited = elem.split('x')
k = 0
for stri in splited:
k = k + 1
if k == 1:
v = stri
u = 1
else:
u = stri
ar = list()
ar.append(v)
ar.append(u)
lst1.append(ar)
dic = dict(lst1)
print(dic)
One more contrib to the zoo: now with list comprehension, splitting, and if
expression:对动物园的另一项贡献:现在具有列表理解、拆分和
if
表达式:
pass1 = [x.split(' x ') for x in l]
# [['FOO', '2'], ['BAR', '11'], ['PERC']]
dict((t[0], int(t[1]) if len(t) > 1 else 1) for t in pass1)
# {'PERC': 1, 'BAR': 11, 'FOO': 2}
Couple of options to choose from几个选项可供选择
data = ["FOO x 2", "BAR x 11", "PERC"]
res = { key : int(value) if value else 1
for key, sep, value in map(lambda s: s.partition(' x '), data) }
res = {}
for item in data:
key, sep, value = item.partition(' x ')
res[key] = int(value) if value else 1
res = {}
for item in data:
key, *value = item.split(' x ')
res[key] = int(value[0]) if value else 1
res = {}
for item in data:
key, value = (item.split(' x ') + [1])[:2]
res[key] = int(value)
# Output - res
{'FOO': 2, 'BAR': 11, 'PERC': 1}
Note that this is assuming that your data will always be in that format, otherwise may need to include .strip()
or other minor changes.请注意,这是假设您的数据始终采用该格式,否则可能需要包含
.strip()
或其他小的更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.