[英]How do I convert a list of strings to a dictionary?
My list is something like this, 我的清单是这样的
['"third:4"', '"first:7"', '"second:8"']
I want to convert this into a dictionary like this... 我想将其转换成这样的字典...
{"third": 4, "first": 7, "second": 8}
How do I do this in Python? 如何在Python中执行此操作?
Here are two possible solutions, one that gives you string values and one that gives you int values: 这是两种可能的解决方案,一种为您提供字符串值,另一种为您提供int值:
>>> lst = ['"third:4"', '"first:7"', '"second:8"']
>>> dict(x[1:-1].split(':', 1) for x in lst)
{'second': '8', 'third': '4', 'first': '7'}
>>> dict((y[0], int(y[1])) for y in (x[1:-1].split(':', 1) for x in lst))
{'second': 8, 'third': 4, 'first': 7}
However, for the sake of readability, you could split the conversion into two steps: 但是,为了便于阅读,您可以将转换分为两个步骤:
>>> lst = ['"third:4"', '"first:7"', '"second:8"']
>>> dct = dict(x[1:-1].split(':', 1) for x in lst)
>>> {k: int(v) for k, v in dct.iteritems()}
Of course this has some overhead since you create a dict twice - but for a small list it doesn't matter. 当然,由于您两次创建字典,这会产生一些开销-但是对于一个小的列表而言,这并不重要。
>>> data
['"third:4"', '"first:7"', '"second:8"']
>>> dict((k,int(v)) for k,v in (el.strip('\'"').split(':') for el in data))
{'second': 8, 'third': 4, 'first': 7}
or 要么
>>> data = ['"third:4"', '"first:7"', '"second:8"']
>>> def convert(d):
for el in d:
key, num = el.strip('\'"').split(':')
yield key, int(num)
>>> dict(convert(data))
{'second': 8, 'third': 4, 'first': 7}
def listToDic(lis):
dic = {}
for item in lis:
temp = item.strip('"').split(':')
dic[temp[0]] = int(temp[1])
return dic
With map and dict
it is very straight forward. 使用
map and dict
可以很直接地进行。
map(func, iterables)
to_dict
will return key, value
which will be consumed by dict
to_dict
将返回key, value
将由dict
def to_dict(item):
return item[0].replace('"',''), int(item[1].replace('"', ''))
>>> items
6: ['"third:4"', '"first:7"', '"second:8"']
>>> dict(map(to_dict, [item.split(':') for item in items]))
7: {'first': 7, 'second': 8, 'third': 4}
help(dict)
class dict(object)
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
>>> dict(map(to_dict, [item.split(':') for item in items]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.