Important: If the value
is a list, then I want to get multiple key, value
tuples for that key
and each item in the list. The values in the dictionary will be of multiple types, including at least strings, ints, and lists.
I have a solution, below, but I'm wondering if there's a more concise way to do this.
# Sample data
d = {'key1': 'string1',
'key2': 15,
'key3': ['item1', 'item2', 'item3', 'item4']}
# This code does what I want
parameters = []
for k, v in d.iteritems():
if isinstance(v, str):
parameters.append((k ,v))
elif isinstance(v, int):
parameters.append((k, v))
elif isinstance(v, list):
for x,y in zip(itertools.repeat(k), v):
parameters.append((x, y))
else:
continue
parameters
# [('key1', 'string1'),
# ('key2', 15),
# ('key3', 'item1'),
# ('key3', 'item2'),
# ('key3', 'item3'),
# ('key3', 'item4')]
I like list comprehensions for readability. Also, I don't see why you need a separate statement for strings and ints. Either you have a list or not.
parameters = []
for k, v in d.iteritems():
if isinstance(v, list):
parameters.extend([(k, i) for i in v])
else:
parameters.append((k, v))
Results:
>>> parameters
[('key3', 'item1'), ('key3', 'item2'), ('key3', 'item3'), ('key3', 'item4'), ('key2', 15), ('key1', 'string1')]
Here is a shorter version with list comprehension:
>>> d = {'key1': 'string1', 'key2': 15, 'key3': ['item1', 'item2', 'item3', 'item4']}
>>> parameters = [(k, v1) for k, v in d.iteritems() for v1 in (v if isinstance(v, list) else [v])]
>>> parameters
[('key3', 'item1'), ('key3', 'item2'), ('key3', 'item3'), ('key3', 'item4'), ('key2', 15), ('key1', 'string1')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.