我是Python新手(2周),陷入一个问题。
我有这本不断增长的字典:
dict1={"some_large_key1":"value1","some_large_key2":"value2",........,"some_large_key1000":"value1000"}
问题1:我想创建一个csv文件,我不想在其中包含一些键,值对。
->一种可能的解决方案是创建一个键列表,而忽略整个列表。
list1=["some_large_key1","some_large_key2","some_large_key3"]
for key,value in dict1:
if key not in list1: #something like this
#do something
else:
#do something
问题2:我不想给出这么大的键名,相反,我只能给出:
list1=["key1","key2",...]
是正确的方法还是我应该考虑其他方法?
最佳答案
您的“ some_large_key1”和“ key1”之间的关系不是很清楚。但是,我认为您可以执行以下操作:
original_dict = {
"some_large_key1": "value1",
"some_large_key2": "value2",
......,
"some_large_key1000": "value1000"
}
to_ignore = ['key1', 'key2', 'key3', ...]
filtered_dict = {key: value for (key, value) in original_dict.items() if key.rsplit('_', 1)[-1] not in to_ignore}
key.rsplit('_', 1)[-1]
的作用是删除some_large_
前缀;您可以用将长键名转换成短键名的功能来代替此部分。关于python - 将字典保存到CSV之前忽略一些键,值对,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33273770/