简体   繁体   English

通过以列表为值的python字典进行迭代

[英]Iterating through a python dictionary with lists as values

I'm trying to iterate through a dictionary that looks like: 我正在尝试遍历如下所示的字典:

    d = {
    "list_one": [
        "hello",
        "two",
        "three"
    ],
    "list_two": [
        "morning",
        "rain"
    ]
}

I'm using the function: 我正在使用的功能:

def combine_words(d):
    for k, v in d.items():
        a = {k: ("|".join(v))}
    return a

When I run this with print, my output is just one key, value pair. 当我用print运行它时,我的输出只是一个键,一对值。 I'm not sure what is happening here. 我不确定这里发生了什么。 My ideal out put would be: 我的理想输出是:

{
'list_one': 'hello|two|three',
'list_two': 'morning|rain'
}
def combine_words(d):
    for k, v in d.items():
        a = {k: ("|".join(v))}
    return a

This constantly reassigns the dictionary to a, and isn't combining the results 这会不断将字典重新分配给a,并且不会合并结果

def combine_words(d):
    a = {}
    for k, v in d.items():
        a[k] =  ("|".join(v))
    return a

Would keep adding new entries to the dictionary 将继续向字典添加新条目

a gets replaced by a new dict each time through your loop. a获得由新的替代dict每次通过你的循环。 You want a dict comprehension. 您要了解字典。

def combine_words(d):
    return {k: "|".join(v) for k, v in d.items()}

The problem is that you change the value of a during every iteration of your for loop because you reassign a . 问题是您在for循环的每次迭代期间都更改了a的值,因为您重新分配a You can modify your code to get around this: 您可以修改代码来解决此问题:

for k, v in d.items():
    a[k] = "|".join(v)

Alternatively, you can use a dict comprehension: 另外,您可以使用dict理解:

return {k: "|".join(v) for k, v in d.items()}

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

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