包含键字符串和列表值的字典

时间:2018-05-25 01:52:02

标签: python

我想将以下字典转换为简单列表:

dict1 = {'fred': ['andrew', 'judy'], 'andrew': ['judy', 'george'], 'judy': ['george'], 'george': ['john']}

我试过了:

for key, value in dict1.items():
    output = [key, value]
    list1.append(output)

ls2 = []
for x in list1:
    for y in x:
        ls2.append(y)
print(ls2)

so I got ls2 = ['fred', ['andrew', 'judy'], 'andrew', ['judy', 'george'], 'judy', ['george'], 'george', ['john']]

如何获得预期输出:

[['fred', 'andrew', 'judy'], ['andrew','judy', 'george'], ['judy', 'george'], ['george', 'john']]

3 个答案:

答案 0 :(得分:3)

list comprehension *splat

x = [[k, *v] for k, v in dict1.items()]

# Result

[['fred', 'andrew', 'judy'], ['andrew', 'judy', 'george'], ['judy', 'george'], ['george', 'john']]

答案 1 :(得分:3)

要在python 2或3下工作,你可以这样做:

代码:

[[k] + v for k, v in dict1.items()]

测试代码:

dict1 = {'fred': ['andrew', 'judy'], 'andrew': ['judy', 'george'],
         'judy': ['george'], 'george': ['john']}

desired = [
    ['fred', 'andrew', 'judy'],
    ['andrew', 'judy', 'george'],
    ['judy', 'george'],
    ['george', 'john']
]

x = [[k] + v for k, v in dict1.items()]
print(x)

结果:

[['judy', 'george'], ['george', 'john'], ['andrew', 'judy', 'george'], ['fred', 'andrew', 'judy']]

答案 2 :(得分:-1)

@Louis ,您还可以使用map()lambda功能来解决您的问题。我提供了 Python3 Python2 的工作示例,如果您使用* Python2 会抛出 SyntaxError 解压缩清单。

您可以在下面的代码示例中查看它(我已经展示了两种方法,包括上述解决方案)。

  

注意:如果列表很大并且您想在控制台中看到它,请使用json模块打印清单。

Python3(Python 3.5.2)

import json

dict1 = {'fred': ['andrew', 'judy'], 'andrew': ['judy', 'george'], 'judy': ['george'], 'george': ['john']}

# 1st way...
l = [[name, *name_list] for name, name_list in dict1.items()]

# pretty printing list
print (json.dumps(l, indent=4))

# 2nd way...
l2 = list(map( lambda name: [name, *dict1[name]],  dict1.keys()))
print(l2)

"""
[
    [
        "fred",
        "andrew",
        "judy"
    ],
    [
        "judy",
        "george"
    ],
    [
        "george",
        "john"
    ],
    [
        "andrew",
        "judy",
        "george"
    ]
]
"""

如果您使用 Python2 运行它,上面的代码将抛出 SyntaxError 。下面是对上述代码进行一些修改后的修复和工作。

Python2(Python 2.7.12)

import json

dict1 = {'fred': ['andrew', 'judy'], 'andrew': ['judy', 'george'], 'judy': ['george'], 'george': ['john']}

# 1st way...
l = [[name] + [name_item for name_item in name_list] for name, name_list in dict1.items()]

# pretty printing list
print (json.dumps(l, indent=4))

# 2nd way...
l2 = list(map( lambda name: [name] + [name_item for name_item in dict1[name]], dict1.keys()))
print(l2)

"""
[
    [
        "fred",
        "andrew",
        "judy"
    ],
    [
        "judy",
        "george"
    ],
    [
        "george",
        "john"
    ],
    [
        "andrew",
        "judy",
        "george"
    ]
]
"""