[英]How do I edit multiple strings inside a list within a dictionary?
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?使用 for 循环,我将如何遍历每个列表的值并根据每个字符串中的某个字符更改它们? 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? for 循环仅返回值 1 已编辑,由于某种原因,它已更改为值 4。如何编辑循环以删除所有值中的字母 v,并将它们全部保存在正确的位置?
Edit: Thank you for all the comments regarding the typo for "key1" instead of "key."编辑:感谢您对“key1”而不是“key”的错字的所有评论。 I must have been trying to test the step-by-step functionality and forgot to change it back to "key."我一定一直在尝试测试分步功能并忘记将其更改回“关键”。
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]
当您使用value.index(value)
时,您正在调用str.index(self)
并且它始终返回 0。您还使用test_dict["key1"]
而不是假定的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.我遍历了索引,因为列表中可能有多个相等/相同的元素。
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.我已使用v[1:]
删除第一个字符,但您可以使用原始代码v.replace('v', '')
代替。
The for loop is only returning value 1 edited, which - for some reason - got changed to value 4. for 循环仅返回值 1 已编辑,由于某种原因,它已更改为值 4。
That's because you looped through the whole dict only replacing test_dict["key1"][0]
each time by the last value iterated.那是因为您循环遍历整个字典,每次只用最后一个迭代值替换test_dict["key1"][0]
。
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.如您所见,您只需更改test_dict["key1"][0]
每次迭代。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.