在将字典保存为CSV之前忽略一些键值对

时间:2015-10-22 05:07:53

标签: python list python-2.7 csv dictionary

我是Python的新手(2周)并且陷入了一个问题 我有这个不断增长的字典:

dict1={"some_large_key1":"value1","some_large_key2":"value2",........,"some_large_key1000":"value1000"}

问题1:我想创建一个csv文件,其中我不想包含一些键值对。
- > 1种可能的解决方案是制作密钥列表并忽略整个列表。

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",...]

这是一种正确的方法还是我应该考虑别的什么?

2 个答案:

答案 0 :(得分:2)

你的“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_前缀;您可以使用将长密钥名称转换为较短密钥的功能替换此部分。

答案 1 :(得分:0)

是的,您可以列出要忽略的键列表。

dict1={"some_large_key1":"value1","some_large_key2":"value2","some_large_key3":"value3"}
ignore_list=['key1', 'key2']
new_dict = {}
for key in dict1:
    if not any(x in key for x in ignore_list):
        key_list=[key]
        value_list=[dict1[key]]
        #make a new dict from above 2 lists  (This will exclude ignore key,value pair)
        for i in range(len(key_list)):
            new_dict[key_list[i]] = value_list[i]
print new_dict

输出:

{'some_new_key3':'value3'}  #Note that key1,key2 is ignored in this output dictionary.