Skip to content Skip to sidebar Skip to footer

Converting Flat Python Dictionary To List Of Dictionaries

I have a dictionary in the following format where I don't know the number of lines or items I'm going to receive: {'line(0).item1':'a', 'line(0).item2':'34', 'line(1).item1':'sd'

Solution 1:

d = {'line(0).item1':'a' ...}

out = collections.defaultdict(list)
for k,v in d.items():
    n,val = re.findall(r'^line\((\d+)\)\.(\w+)$', k)[0]
    out[int(n)].append((val,v))

my_list = [dict(out[v]) for v in sorted(out)]

and the output will be the expected:

[{'item2': '34', 'item1': 'a'}, {'item2': '2', 'item3': 'fg', 'item1': 'sd'}, {'item1': 'f'}]

Solution 2:

I'd go with an intermediate dictionary of dictionaries, since there is no way of knowing how many "lines" you'd have at the end and you can't insert a new element at the end of the list later.

It should be simple enough to iterate over every element in this dict and parse it into the line number and key. You could then easily transfer the new dict into the list you desired. A possible implementation could be:

intermediate_dict = {}
for entry in my_dict:
    line_string, key = entry
    line_number = int(line_string[line_string.index('(') + 1: line_string.index(')')])
    if line_number not in intermediate_dict:
        intermediate_dict[line_number] = {}
    intermediate_dict[line_number][key] = my_dict[entry]

new_list = []
for i in xrange(len(intermediate_dict)):
    new_list.append(intermediate_dict[i])

Post a Comment for "Converting Flat Python Dictionary To List Of Dictionaries"