【问题标题】:Removing a Key from a dict if value is not found in list如果在列表中找不到值,则从字典中删除键
【发布时间】:2022-10-14 04:04:16
【问题描述】:

我有一个字典,其中一些键不是我的 df 中的列名,这会导致出现 KeyError 我想删除/忽略字典中与列名不匹配的所有键

import pandas as pd
 
filename='template'
data= [['','','','','','','','Auto','','','','','']]
df= pd.DataFrame(data,columns=['first','last','state','lang','country','company','email','industry',
                                'System_Type__c','AccountType','segment','existing','permission'])
 
valid= {'industry': ['Automotive'],
        'SME Vertical': ['Agriculture'],
        'System_Type__c': ['Access'],
        'AccountType': ['Commercial']}
 
col_list=[col for col in df]
key = [k for k in valid if k in col_list]

我看到有些人使用 del 或 pop()

我想要的输出是这样的

valid= {'industry': ['Automotive'],
        'System_Type__c': ['Access'],
        'AccountType': ['Commercial']}

如何从字典中删除键?

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    这是一种方法

    # using dictionary comprehension, iterate through dict and 
    # recreate dictionary when key exists in df.columns
    
    valid={k:v for k, v in valid.items() if k in df.columns.values}
    valid
    
    {'industry': ['Automotive'],
     'System_Type__c': ['Access'],
     'AccountType': ['Commercial']}
    

    【讨论】:

      【解决方案2】:

      因为字典是键值对,删除键孤儿值有效地为您提供所需的内容。用法是这样的:

      del your_dict['your_key']
      

      https://docs.python.org/3/tutorial/datastructures.html#dictionaries

      【讨论】:

        【解决方案3】:

        确保将查找列表转换为一个集合以获得O(n) 操作而不是O(n^2)

        valid = {'industry': ['Automotive'],
                 'SME Vertical': ['Agriculture'],
                 'System_Type__c': ['Access'],
                 'AccountType': ['Commercial']}
        
        to_keep = set(df.columns)
        
        valid = {k: v for k, v in valid.items()
                 if k in to_keep}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-10-26
          • 2020-11-01
          • 2017-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-28
          相关资源
          最近更新 更多