Convert Python Flat Dictionary to Dictionary List

I have a dictionary in the following format, where I do not know the number of lines or elements that I am going to get:

{'line(0).item1':'a', 'line(0).item2':'34', 'line(1).item1':'sd', 'line(1).item2':'2', 'line(1).item3':'fg', 'line(2).item1':'f' ... } 

What is the most pythonic way to parse this into a list of dictionaries in the following format:

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

Thanks in advance.

+4
source share
2 answers
 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 expected:

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

I would go with an intermediate dictionary of dictionaries, since there is no way to find out how many β€œlines” you would have at the end, and you cannot insert a new element at the end of the list later.

It should be simple enough to iterate over each element in this dict and parse it for line number and key. Then you can easily transfer the new dict to the list you need. A possible implementation may 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]) 
0
source

All Articles