如何从Python中的字典列表中获取某些键的不同值

时间:2016-03-29 18:47:49

标签: python python-3.x

我在为某些键选择不同的值时遇到问题。 场景:我的代码通过odbc驱动程序调用sql server中的表。 sql表有10列,我通过1次调用查询所有10列。但是在我的代码中,我不需要同时使用10列,我需要同时说5列和它们的独特价值。我可以通过另一个db调用来做到这一点,但我想避免多个db调用。任何python方式来解决这个问题? 例如:

my_list = [{'workflow_id':1,'file':'aaa','table':'table1','order':1},
           {'workflow_id':1,'file':'aaa','table':'table1','order':2},
           {'workflow_id':1,'file':'aaa','table':'table2','order':1},
           {'workflow_id':1,'file':'aaa','table':'table2','order':2}]

# Expecting below output
my_new_list = [{'workflow_id':1,'file':'aaa','table':'table1'},
               {'workflow_id':1,'file':'aaa','table':'table2'}]

2 个答案:

答案 0 :(得分:0)

使用SELECT DISTINCT column FROM table

请参阅http://www.w3schools.com/sql/sql_distinct.asp

答案 1 :(得分:0)

对于给定的输入:

my_list = [{'workflow_id':1,'file':'aaa','table':'table1','order':1},
           {'workflow_id':1,'file':'aaa','table':'table1','order':2},
           {'workflow_id':1,'file':'aaa','table':'table2','order':1},
           {'workflow_id':1,'file':'aaa','table':'table2','order':2}]

这是一种Python方法:

import copy

def remove_order(data):
    result = copy.deepcopy(data)
    for entry in result:
        if 'order' in entry:
            del entry['order']
    return result

def remove_duplicates(data):
    result = list()
    for entry in data:
        if entry not in result:
            result.append(entry)
    return result

my_new_list = remove_duplicates(remove_order(my_list))

print my_new_list

这是输出:

[{'table': 'table1', 'workflow_id': 1, 'file': 'aaa'}, 
 {'table': 'table2', 'workflow_id': 1, 'file': 'aaa'}]

请注意使用deepcopy,以防维护原始列表的内容。