简体   繁体   English

给定一个字典,其中值可能是不同的类型,如何将python字典简洁地转换为元组列表?

[英]How do I concisely convert a python dictionary to a list of tuples, given a dictionary in which the values may be different types?

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. 重要提示:如果该value是一个列表,则我想获取多个key, valuekey和列表中每个项目的key, value元组。 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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM