0

我的清单是这样的,

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

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

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

我如何在 Python 中做到这一点?

4

4 回答 4

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 - 但对于一个小列表,这并不重要。

于 2012-05-07T09:17:32.977 回答
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}
于 2012-05-07T09:18:34.893 回答
1
def listToDic(lis):
    dic = {}
    for item in lis:
        temp = item.strip('"').split(':')
        dic[temp[0]] = int(temp[1])
    return dic
于 2012-05-07T09:35:37.163 回答
0

有了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]))
于 2012-05-07T10:30:38.893 回答