如何从python中的字典列表中提取特定值

时间:2019-09-22 10:25:18

标签: python list dictionary

我有一个字典列表,如下所示,我想使用python提取partID和特定orderID的相应数量,但是我不知道该怎么做。

dataList = [{'orderID': 'D00001', 'customerID': 'C00001', 'partID': 'P00001', 'quantity': 2},
 {'orderID': 'D00002', 'customerID': 'C00002', 'partID': 'P00002', 'quantity': 1},
 {'orderID': 'D00003', 'customerID': 'C00003', 'partID': 'P00001', 'quantity': 1},
 {'orderID': 'D00004', 'customerID': 'C00004', 'partID': 'P00003', 'quantity': 3}]

例如,当我在dataList中搜索特定的orderID == 'D00003'时,我想同时收到partID ('P00001')和相应的quantity (1)指定的顺序。您将如何处理?非常感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

要视情况而定。

您不会花很多时间,您可以遍历字典列表,直到找到“正确的”字典为止:

search_for_order_id = 'D00001'
for d in dataList:
    if d['orderID'] == search_for_order_id:
        print(d['partID'], d['quantity'])
        break  # assuming orderID is unique

输出

P00001 2

由于此解决方案为O(n),因此如果您要进行多次搜索,它将累加起来。

在那种情况下,最好将数据转换成字典字典,用orderID作为外键(同样,假设orderID是唯一的):

 better = {d['orderID']: d for d in dataList}

这也是O(n),但您只需支付一次。任何后续查找都是O(1)字典查找:

search_for_order_id = 'D00001'
print(better[search_for_order_id]['partID'], better[search_for_order_id]['quantity'])

也输出

P00001 2

答案 1 :(得分:0)

我相信您想熟悉pandas软件包,它对于数据分析非常有用。如果您遇到这些问题,建议您花点时间在pandas中学习教程。它可以做很多事情,并且非常受欢迎。

您的dataListDataFrame结构非常相似,因此您要查找的内容很简单:

import pandas as pd
df = pd.DataFrame(dataList)
df[df['orderID']=='D00003']

答案 2 :(得分:0)

要获取partID,您可以使用filter函数。

myData = [{"x": 1, "y": 1}, {"x": 2, "y": 5}]

filtered = filter(lambda item: item["x"] == 1) # Search for an object with x equal to 1

# Get the next item from the filter (the matching item) and get the y property.
print(next(filtered)["y"])

您应该能够将此应用于您的情况。

答案 3 :(得分:0)

您可以使用此:

results = [[x['orderID'], x['partID'], x['quantity']] for x in dataList]
for i in results:
    print(i)

results = [['Order ID: ' + x['orderID'], 'Part ID: ' + x['partID'],'Quantity: 
' + str(x['quantity'])] for x in dataList]