如何从python 3中的字典列表中获取键和值对

时间:2016-02-23 19:12:39

标签: python-3.x

我是Python开发人员的新手。下面是我的测试代码:

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.我需要找到来自column_list的SOURCE_COLUMN的值是否在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'}]

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

制作new_dicts = [{col:my_dict[col] for col in source_cols if col in my_dict} for my_dict in my_dicts] 的另一种方法是通过列表理解:

{{1}}

如果您喜欢Shubit的答案,请考虑提高它:)