How can I make a one line generator expression to generate these two different lists

Viewed 61

I am writing a program which parses lists like this.

['ecl:gry', 'pid:860033327', 'eyr:2020', 'hcl:#fffffd', 'byr:1937', 'iyr:2017', 'cid:147', 'hgt:183cm']

I want to turn this list into a dictionary of the key value pairs which I have done here:

keys = []
values = []

for string in data:
    pair = string.split(':')
    keys.append(pair[0])
    values.append(pair[1])

zipped = zip(keys, values)
self.dic = dict(zipped)
print(self.dic)

I know that I can use list comprehension to make one of the lists at a time like this

keys = [s.split(':')[0] for s in data]
values = [s.split(':')[1] for s in data]

This requires two loops so the first code example would be better, but is there a way to generate both lists using one generator with unpacking and then zip the two together?

3 Answers
l = ['ecl:gry', 'pid:860033327', 'eyr:2020', 'hcl:#fffffd',
     'byr:1937', 'iyr:2017', 'cid:147', 'hgt:183cm']

dict(e.split(':') for e in l)

You can dict comprehension it easily:

your_dict = {x.split(':')[0]: x.split(':')[1] for x in data}

You can also prevent from using split two times and use generator:

your_dict = dict(x.split(':') for x in data)

Which seems even cleaner...

I did it like this:

self.dic = {}
for e in data:
    k, v = e.split(':')
    self.dic[k] = v
Related