简体   繁体   中英

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. 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

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. 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 . 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:

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

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.

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