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

时间:2012-05-07 09:14:09

标签: python list dictionary

我的清单是这样的,

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

我想把它转换成这样的字典......

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

我如何在Python中执行此操作?

4 个答案:

答案 0 :(得分:6)

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

当然,由于你创建了一个dict两次,这有一些开销 - 但是对于一个小列表来说并不重要。

答案 1 :(得分:3)

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

答案 2 :(得分:1)

def listToDic(lis):
    dic = {}
    for item in lis:
        temp = item.strip('"').split(':')
        dic[temp[0]] = int(temp[1])
    return dic

答案 3 :(得分:0)

使用map and dict非常简单。

map 的

语法

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