繁体   English   中英

如何将字符串列表转换为字典?

[英]How do I convert a list of strings to a dictionary?

我的清单是这样的

['"third:4"', '"first:7"', '"second:8"']

我想将其转换成这样的字典...

{"third": 4, "first": 7, "second": 8}

如何在Python中执行此操作?

这是两种可能的解决方案,一种为您提供字符串值,另一种为您提供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}

但是,为了便于阅读,您可以将转换分为两个步骤:

>>> 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()}

当然,由于您两次创建字典,这会产生一些开销-但是对于一个小的列表而言,这并不重要。

>>> 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}

要么

>>> 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

使用map and dict可以很直接地进行。

地图语法

map(func, iterables)

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.

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