我有一本字典。
样本:
keyList = ['0','1','2']
valueList = [{'Name': 'Nick', 'Age': 39, 'Country': 'UK'}, {'Name': 'Steve', 'Age': 19, 'Country': 'Spain'}, {'Name': 'Dave', 'Age': 23, 'Country': 'UK'}]
d = {}
for i in range(len(keyList)):
d[keyList[i]] = valueList[i]输出:
{'0': {'Name': 'Nick', 'Age': 39, 'Country': 'UK'}, '1': {'Name': 'Steve', 'Age': 19, 'Country': 'Spain'}, '2': {'Name': 'Dave', 'Age': 23, 'Country': 'UK'}}我想做两件事:
Name )中的字符串或int值进行筛选,忽略大小写。即删除任何找到字符串/int的key/value。因此,如果在Name中找到'Nick‘,则完全删除key '0’及其值:{'1': {'Name': 'Steve', 'Age': 19, 'Country': 'Spain'}, '2': {'Name': 'Dave', 'Age': 23, 'Country': 'UK'}}
keys,忽略大小写.{'1': {'Name': 'Steve', 'Age': 19, 'Country': 'Spain'}}
我本来希望下面这个词只适用于一个字符串,但我认为只有当它只是一本字典而不是一本字典时,它才能起作用,所以它不适用于我:
filtered_d = {k: v for k, v in d.items() if "nick".casefold() not in v["Name"]}有什么建议吗?非常感谢
发布于 2022-09-06 11:03:28
假设字典中有一个层次的嵌套(而不是字典字典),您可以使用以下函数,根据提供的值迭代键和过滤器:
from typing import List
def remove_from_dict(key_name: str, values: List[str], dictionary: dict):
values = [value.casefold() for value in values]
filtered_dict = {
key: inner_dict
for key, inner_dict in dictionary.items()
if inner_dict[key_name].casefold() not in values
}
return filtered_dict
dictionary = {
"0": {"Name": "Nick", "Age": 39, "Country": "UK"},
"1": {"Name": "Steve", "Age": 19, "Country": "Spain"},
"2": {"Name": "Dave", "Age": 23, "Country": "UK"},
}
# Output: {'1': {'Name': 'Steve', 'Age': 19, 'Country': 'Spain'}, '2': {'Name': 'Dave', 'Age': 23, 'Country': 'UK'}}
print(remove_from_dict("Name", ["Nick"], dictionary))
# Output: {'1': {'Name': 'Steve', 'Age': 19, 'Country': 'Spain'}}
print(remove_from_dict("Country", ["uK", "Italy", "New Zealand"], dictionary))更新:
如果我们想要计算部分匹配,我们必须使用re模块。
import re
from typing import List, Optional
dictionary = {
"0": {"Name": "Nick", "Age": 39, "Country": "UK"},
"1": {"Name": "Steve", "Age": 19, "Country": "Spain"},
"2": {"Name": "Dave", "Age": 23, "Country": "UK"},
}
def remove_from_dict(
key_name: str,
values: List[str],
dictionary: dict,
use_regex: Optional[bool] = False,
):
values = [value.casefold() for value in values]
regular_comparator = lambda string: string.casefold() not in values
# if the string matches partially with anything in the list,
# we need to discard that dictionary.
regex_comparator = lambda string: not any(
re.match(value, string.casefold()) for value in values
)
comparator = regex_comparator if use_regex else regular_comparator
filtered_dict = {
key: inner_dict
for key, inner_dict in dictionary.items()
if comparator(inner_dict[key_name])
}
return filtered_dict
# Output: {}, all dictionaries removed
print(remove_from_dict("Country", ["uK", "Spa"], dictionary, use_regex=True))https://stackoverflow.com/questions/73620761
复制相似问题