More Pythonic Way To Write This Block (and Elimnate: Valueerror: Dictionary Update Sequence Element #0 Has Length 1; 2 Is Required)
Solution 1:
You need to drop the list wrapper; just produce the tuples:
row_data = dict((make_key(x), make_value(x)) for x in records)
You were producing a list with one element each, a tuple.
If you are using Python 2.7 or newer, you can also use a dictionary comprehension:
row_data = {make_key(x): make_value(x) for x in records}
Your make_value
could be expressed by using a operator.itemgetter()
object:
fromoperator import itemgetter
make_value = itemgetter(
'f7', 'f1', 'f4', 'f9', 'f2', 'f8', 'f10', 'f11', 'f12', 'f17',
'f18', 'f19', 'f14', 'f15', 'f16', 'f17', 'f20')
The make_key()
function can make use of the fact that you can pull out attributes from an object; {0.f1}
would interpolate the f1
attribute of the first positional argument to the str.format()
method; make use of this to create a bound str.format()
method that takes just one positional argument:
make_key = '{0.f1}/{0.f2}/{0.f3}'.format
Solution 2:
A few different things you can do to make it simpler :)
No need for a separate make_key function definition, you already have one:
make_key = '{0.f1}/{0.f2}/{0.f3}'.format
Beyond that, depending on your Python version you can also use dict comprehensions:
row_data = {make_key(x): make_value(x) for x in records}
Post a Comment for "More Pythonic Way To Write This Block (and Elimnate: Valueerror: Dictionary Update Sequence Element #0 Has Length 1; 2 Is Required)"