[英]Python dictionary where values are lists, how to remove Xth item from every list value
I have dictionary in the form of:我有以下形式的字典:
dict_one = { key2: [val1, val2, val3], key2: [val1, val2, val3] }
I want to remove 'val3' from every element in the dictionary.我想从字典中的每个元素中删除 'val3'。 I believe this should be possible via a for loop but I can't seem to get it correct.
我相信这应该可以通过 for 循环实现,但我似乎无法正确理解。 I've tried the following:
我尝试了以下方法:
for lst in dict_one:
dict_one.pop(dict_one[lst][2])
This is intended, I believe, to remove both key and value.我相信,这是为了删除键和值。 It returned a 'keyerror' error message.
它返回了“keyerror”错误消息。 dict_one.remove() is clearly not going to work as it's meant for lists.
dict_one.remove() 显然不起作用,因为它适用于列表。 It seems like what I'm trying to do should be relatively simple but I seem to be missing something.
看起来我想做的事情应该相对简单,但我似乎遗漏了一些东西。
(FYI, it seems like if I only wanted to delete a subset of the 'val3' items, I could follow the approach here: Remove element in dictionary of lists ) (仅供参考,如果我只想删除“val3”项目的子集,我可以按照这里的方法: 删除列表字典中的元素)
First, to remove an item from a list:首先,从列表中删除一个项目:
l = [val1, val2, val3]
l.remove(val3)
Now looping through lists in dictionary:现在遍历字典中的列表:
dict_once = {key1: [val1, val2, val3], key2: [val1, val2, va3]}
for inner_list in dict_one.values():
inner_list.remove(val3)
Or, looping through using keys:或者,使用键循环:
for key in dict_one:
dict_one[key].remove(val3)
To get a specific item from list of dictionary:要从字典列表中获取特定项目:
for lst in dict_one:
print(dict_one.get(lst)[item_num])
to modify an entry:修改条目:
for lst in dict_one:
dict_one[lst] = new_value
print(dict_one.get(lst))
The changes you wanted to your lists:您想要对列表进行的更改:
dict_one = { 'key2': ['val1', 'val2', 'val3'], 'key3': ['val1', 'val2', 'val3'] }
for lst in dict_one:
dict_one[lst] = dict_one.get(lst)[:-1]
print(dict_one.get(lst))
One way using dict
comprehension:使用
dict
理解的一种方法:
dict_one = {'key2': ['val1', 'val2', 'val3'], 'key3': ['val1', 'val2', 'val3']}
dict_two = {k: v[:-1] for k, v in dict_one.items()}
print(dict_two)
Output: Output:
{'key2': ['val1', 'val2'], 'key3': ['val1', 'val2']}
dict_one = {"key2": ["val1", "val2", "val3"], "key3": ["val1", "val2", "val3"]}
for lst in dict_one:
dict_one[lst] = dict_one.get(lst)[:-1]
print dict_one
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.