I have a list
of dict
. Need to convert it to list
of namedtuple
(preferred) or simple tuple
while to split first variable by whitespace.
What is more pythonic way to do it?
I simplified my code a little. Comprehensions, gen expressions and itertools usage welcomed.
Data-in:
dl = [{'a': '1 2 3',
'd': '*',
'n': 'first'},
{'a': '4 5',
'd': '*', 'n':
'second'},
{'a': '6',
'd': '*',
'n': 'third'},
{'a': '7 8 9 10',
'd': '*',
'n': 'forth'}]
Simple algorithm:
from collections import namedtuple
some = namedtuple('some', ['a', 'd', 'n'])
items = []
for m in dl:
a, d, n = m.values()
a = a.split()
items.append(some(a, d, n))
Output:
[some(a=['1', '2', '3'], d='*', n='first'),
some(a=['4', '5'], d='*', n='second'),
some(a=['6'], d='*', n='third'),
some(a=['7', '8', '9', '10'], d='*', n='forth')]
Use the items() Function to Convert a Dictionary to a List of Tuples in Python. The items() function returns a view object with the dictionary's key-value pairs as tuples in a list. We can use it with the list() function to get the final result as a list.
Python's dictionary class has three methods for this purpose. The methods items(), keys() and values() return view objects comprising of tuple of key-value pairs, keys only and values only respectively. The in-built list method converts these view objects in list objects.
Below, @Petr Viktorin points out the problem with my original answer and your initial solution:
WARNING! The values() of a dictionary are not in any particular order! If this solution works, and a, d, n are really returned in that order, it's just a coincidence. If you use a different version of Python or create the dicts in a different way, it might break.
(I'm kind of mortified I didn't pick this up in the first place, and got 45 rep for it!)
Use @eryksun's suggestion instead:
items = [some(m['a'].split(), m['d'], m['n']) for m in dl]
My original, incorrect answer. Don't use it unless you have a list of OrderedDict
.
items = [some(a.split(), d, n) for a,d,n in (m.values() for m in dl)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With