2016-02-23 84 views
1

我是Python開發新手。下面是我的測試代碼:如何從Python 3中的字典列表中獲取鍵和值對

my_dict = [{'IS_DUMMY': False, 'FACT_CURRENCY': '$', 'RETAILER_NAME': 'kohls', 'RETAILER_KEY': 5, 'ACTIVE': 'Y'},{'IS_DUMMY': False, 'FACT_CURRENCY': '$', 'RETAILER_NAME': 'target', 'RETAILER_KEY': 100, 'ACTIVE': 'Y'}] 

column_list = [{'SOURCE_COLUMN':'FACT_CURRENCY', 'TARGET_COLUMN':'CURRENCY'},{'SOURCE_COLUMN':'RETAILER_NAME', 'TARGET_COLUMN':'RETAILER'}, 
{'SOURCE_COLUMN':'RETAILER_KEY', 'TARGET_COLUMN':'KEY'},{'SOURCE_COLUMN':'ACTIVE', 'TARGET_COLUMN':'ACTIVE'}] 

這裏是我的問題:1, 我需要找到如果SOURCE_COLUMN從column_list中的值是my_dict可用(我能找到) 2。我需要創建一個dict列表,其中只包含來自my_dict中column_list的匹配值。所以我的新字典的名單看起來象下面這樣:

my_new_dict = [{'FACT_CURRENCY': '$', 'RETAILER_NAME': 'kohls', 'RETAILER_KEY': 5, 'ACTIVE': 'Y'},{'FACT_CURRENCY': '$', 'RETAILER_NAME': 'target', 'RETAILER_KEY': 100, 'ACTIVE': 'Y'}] 

回答

1

爲了讓您的問題更具可讀性,你應該把代碼放在多餘的線條,並通過4個空格縮進他們,就像這樣:

# your data: 
my_dicts = [{'IS_DUMMY': False, 'FACT_CURRENCY': '$', 'RETAILER_NAME': 'kohls', 'RETAILER_KEY': 5, 'ACTIVE': 'Y'},{'IS_DUMMY': False, 'FACT_CURRENCY': '$', 'RETAILER_NAME': 'target', 'RETAILER_KEY': 100, 'ACTIVE': 'Y'}] 
column_list = [{'SOURCE_COLUMN':'FACT_CURRENCY', 'TARGET_COLUMN':'CURRENCY'},{'SOURCE_COLUMN':'RETAILER_NAME', 'TARGET_COLUMN':'RETAILER'}, {'SOURCE_COLUMN':'RETAILER_KEY', 'TARGET_COLUMN':'KEY'},{'SOURCE_COLUMN':'ACTIVE', 'TARGET_COLUMN':'ACTIVE'}] 

# seems like we only need the SOURCE_COLUMN entries from the column_list 
source_cols = [col['SOURCE_COLUMN'] for col in column_list] 

# iterate over my_dicts and create a new dictionary for each my_dict using 
new_dicts = [] 
for my_dict in my_dicts: 
    new_dicts.append({col:my_dict[col] for col in source_cols if col in my_dict}) 

另請參閱PEP 274 -- Dict Comprehensions

+0

非常感謝! – Pradeep

0

使new_dicts將通過列表理解的另一種方式:

new_dicts = [{col:my_dict[col] for col in source_cols if col in my_dict} for my_dict in my_dicts] 

如果你喜歡Shubit的回答,請考慮投它:)

+0

new_dicts.append({col ['SOURCE_COLUMN']:my_dict [col ['TARGET_COLuUMN'] for col in column_list if col ['TARGET_COLUMN'] in my_dict}) – Shubit

+0

@ k-menyah您可以使用list comprehension,但爲了可讀性我寧願不要,即使如此,我喜歡這個緊湊的語法:) – Shubit

+0

謝謝。有沒有什麼辦法可以在新字典中的column_list中使用目標列更新源列? @Shubit – Pradeep

相關問題