Pythonic Way To Flatten A Dictionary Into A List Using List Comprehension
Solution 1:
You can do it like this:
fields = ("field1", "field2", "field3")
output = [[k] + [mydict[k].get(x) for x in fields] for k in mydict]
In that code we iterate dict keys and add them with selected subset of second-level dictionaries values.
Solution 2:
This might solve your problem:
defcreate_list_from_dict1(mydict):
return [
(key,) + tuple(v for _, v insorted(val.items()))
for key, val insorted(mydict.items())
]
This assumes that:
- You want the same order for the values in each tuple in the output;
- You want the outer and inner keys sorted alphabetically (otherwise you'll need an appropriate
key
forsorted
); - You want the values for all of the keys from the inner dictionaries; and
- All of the dictionaries in the input contain all of the same keys (otherwise you'll get more/fewer entries in each tuple, and no guarantee they're aligned).
Note the use of .items
in both inner and outer loops to sort both by key (two-tuples are sorted on the first element, with the second only used to break ties) and the conventional _
identifier for "we won't be using this any more".
In use:
>>> create_list_from_dict1({
'hello': {'foo': 1, 'bar': 2, 'baz': 3},
'world': {'foo': 4, 'bar': 5, 'baz': 6},
})
[('hello', 2, 3, 1), ('world', 5, 6, 4)]
Solution 3:
If order doesn't matter...
def create_list_from_dict1(mydict):
output = []
for k, v in openint_dict.items():
fields = [value for key, value in v.items()]
output.append( tuple([k] + fields )
return output
If order matters you either need to do as you did and call out the fields specifically...or you need to used an OrderedDict
for the sub-dicts.
Solution 4:
Python dict
s have keys()
and values()
methods to get a list of the keys and values. If order of the fields is not important:
[(k,) + tuple(v.values()) for k, v in mydict]
If the ordering of the values does matter:
[(k,) + tuple([v[i] for i in sorted(v.keys())]) for k, v in mydict]
Note that the second option would be identical to the first without the call to sorted()
. The order depends on how things were added to the subdict, so you should use the second option as much as possible.
Solution 5:
def create_list_from_dict1(mydict):
return [tuple([k]+list(v.values())) for k,v in openint_dict.items()]
doesn't use the fields' names and produces the same result.
In Python 3.5, you can just type (because starred expressions are allowed everywhere):
defcreate_list_from_dict1(mydict):
return [(k,*v.values()) for k,v in openint_dict.items()]
Post a Comment for "Pythonic Way To Flatten A Dictionary Into A List Using List Comprehension"