Search code examples
pythonlistdictionaryreplacelist-comprehension

Python: altering items in a list when the list is a value of a dictionary


This may sound simple, but I can't wrap my head around it.

My dictionary:

MY_DICT = {
    "foo":[
        "bar/",
        "baz"
    ],
    "another_key": [
        "1_item",
        "2_item/".
    ],
}`

I need to remove the trailing slash from "bar" and "2_item", and put the values back into the dict.

This is what I have (and it works):

for key in MY_DICT:
    MY_DICT[key] = [item.rstrip('/') for item in MY_DICT[key])

But I'm wondering if there's a more 'pythonic' way to do this using dict/list comprehensions.

I want to remove all trailing slashes from every item in a dictionary, using dict comprehensions


Solution

  • Your solution is fine for modifying the dictionary in place.

    If you want to create a new dictionary, you can use a dictionary comprehension with an embedded list comprehension.

    new_dict = {key: [item.rstrip('/') for item in value] 
                for key, value in MY_DICT.items()}