Reputation: 503
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?
Upvotes: 0
Views: 194
Reputation: 20419
With map and dict
it is very straight forward.
map(func, iterables)
to_dict
will return key, value
which will be consumed by 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]))
Upvotes: 0
Reputation: 2441
def listToDic(lis):
dic = {}
for item in lis:
temp = item.strip('"').split(':')
dic[temp[0]] = int(temp[1])
return dic
Upvotes: 1
Reputation: 133534
>>> 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}
Upvotes: 3
Reputation: 318488
Here are two possible solutions, one that gives you string values and one that gives you int values:
>>> 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.
Upvotes: 6