Home > database >  How do I edit multiple strings inside a list within a dictionary?
How do I edit multiple strings inside a list within a dictionary?

Time:07-16

I'm currently working with a data structure that uses a dictionary where the value for each key is a list. For the sake of the question, I've simplified my structure into an easy-to-understand example.

Using a for loop, how would I loop through the values of each list and change them based on a certain character in each string? This is what I have so far:

test_dict = {"key1": ["value1", "value2"], "key2": ["value3", "value4"]}

for key in test_dict:
    for value in test_dict[key]:
        if "v" in value:
            test_dict["key1"][value.index(value)] = value.replace("v", "")

Output:

{'key1': ['alue4', 'value2'], 'key2': ['value3', 'value4']}

The for loop is only returning value 1 edited, which - for some reason - got changed to value 4. How do I edit the loop to remove the letter v in all the values, and keep them all in the right place?

CodePudding user response:

First, let's clarify the types:

from typing import *
test_dict: Dict[str, List[str]]
key: str
value: str

And when you use value.index(value), you are calling str.index(self) and it always returns 0. You also used test_dict["key1"] instead of the supposed test_dict[key]

Final code:

test_dict = {"key1": ["value1", "value2"], "key2": ["value3", "value4"]}

for key in test_dict:
    for i in range(len(test_dict[key])): # better in case there are multiple same elements
        if "v" in test_dict[key][i]:
            test_dict[key][i] = test_dict[key][i].replace("v", "")

I looped over the indexes because there may be multiple equal/same elements in the list.

CodePudding user response:

You can nest dict comprehension and list comprehension:

test_dict = {"key1": ["value1", "value2"], "key2": ["value3", "value4"]}

output = {k: [v[1:] for v in lst] for k, lst in test_dict.items()}
print(output) # {'key1': ['alue1', 'alue2'], 'key2': ['alue3', 'alue4']}

I've used v[1:] to remove the first character, but you can use your original code v.replace('v', '') instead.

CodePudding user response:

The for loop is only returning value 1 edited, which - for some reason - got changed to value 4.

That's because you looped through the whole dict only replacing test_dict["key1"][0] each time by the last value iterated.

To be more specific let's eval your code and print the result of each iteration as well as the index of the value:

test_dict = {"key1": ["value1", "value2"], "key2": ["value3", "value4"]}

for key in test_dict:
    for value in test_dict[key]:
        if "v" in value:
            test_dict["key1"][value.index(value)] = value.replace("v", "")
            print(test_dict)
            print(value.index(value))

Output is:

{'key1': ['alue1', 'value2'], 'key2': ['value3', 'value4']}
0
{'key1': ['alue2', 'value2'], 'key2': ['value3', 'value4']}
0
{'key1': ['alue3', 'value2'], 'key2': ['value3', 'value4']}
0
{'key1': ['alue4', 'value2'], 'key2': ['value3', 'value4']}
0

As you can see you only change test_dict["key1"][0] for each iteration.

As for the answer here's how I'd do to be as simple and readable as possible:

for k, v in test_dict.items():
     test_dict[k] = [value.replace("v", "") for value in v]
  • Related