Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list of dictionaries in python

I have a following data set that I read in from a text file:

all_examples=   ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']

I need to create a list of dictionary as follows:

lst = [ 
{"A":1, "B":2, "C":4, "D":4 },
{"A":1, "B":1, "C":4, "D":5 } 
]

I tried using an generator function but it was hard to create a list as such.

attributes = 'A,B,C'
def get_examples():

    for value in examples:
        yield dict(zip(attributes, value.strip().replace(" ", "").split(',')))
like image 544
Clint Whaley Avatar asked Dec 15 '22 08:12

Clint Whaley


1 Answers

A one liner, just for fun:

all_examples = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))

Produces:

[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, 
 {'A': 1, 'C': 4, 'B': 1, 'D': 5}]

As a bonus, this will work for longer sequences too:

all_examples = ['A,1,1,1', 'B,2,1,2', 'C,4,4,3', 'D,4,5,6']

Output:

[{'A': 1, 'C': 4, 'B': 2, 'D': 4},
 {'A': 1, 'C': 4, 'B': 1, 'D': 5},
 {'A': 1, 'C': 3, 'B': 2, 'D': 6}]

Explanation:

map(dict, zip(*[[(s[0], int(x)) for x in s.split(',')[1:]] for s in all_examples]))
  • [... for s in all_examples] For each element in your list:
  • s.split(',')[1:] Split it by commas, then take each element after the first
  • (...) for x in and turn it into a list of tuples
  • s[0], int(x) of the first letter, with that element converted to integer
  • zip(*[...]) now transpose your lists of tuples
  • map(dict, ...) and turn each one into a dictionary!
like image 141
tzaman Avatar answered Jan 02 '23 11:01

tzaman