带条件的字典嵌套列表

时间:2019-09-16 04:33:13

标签: python list dictionary

我觉得我对此感到迷茫...

所以我两次添加了评论,因为我认为我没有任何意义。我的代码更多是psuedocode,因为我一直在圈子里逛逛。

这个想法是要有一个包含字典的项目清单,其中包含各种价格,并根据该价格具有不同数量。理想情况下,我想按名称的顺序插入它们,然后按价格的顺序插入

这是我到目前为止所拥有的。

MyList = []
print(MyList)

def insertIntoList(listToAdd):
    """insert into MyList if name not in first element of each list
    if the name is in the list, check to see if the first element of
    any dictionary has the same value, if it does, add the last element
    to the last element of that dictionary element"""
    if len(MyList) == 0:
        MyList.append(listToAdd)

    for ind, i in enumerate(listToAdd):
        #for each list in listToAdd
        if i in MyList:
            #if name in MyList
            for item in listToAdd[1][0]:
                if item in MyList[ind] == listToAdd[1][0]:
                    #if the first element of each dictionary 
                    # in the list is equivalent to the first element
                    # of the dict, then increment the last element
                    MyList += listToAdd[1][1]
                else:
                    #otherwise add the new dictionary to the list
                    MyList.append(listToAdd[1])
        else:
            #otherwise if name isnt in MyList
            MyList.append(listToAdd)



insertIntoList(["Foo", [{1010:10101010}]])
insertIntoList(["Bar", [{0:1}]])
insertIntoList(["Bar", [{1:1}]])
insertIntoList(["Foo", [{1010:5}]])
print(MyList)

这应该打印;

[["Bar", [{0:1}, {1:1}]], ["Foo", [{1010:10101015}]]]

2 个答案:

答案 0 :(得分:2)

也许您应该使用better数据结构,

$ cat price.py
from collections import defaultdict

d = defaultdict(dict)

def insert(key, value):
    for k,v in value.items():
        d[key].setdefault(k, 0)
        d[key][k] += v

insert("Foo", {1010:10101010})
insert("Bar", {0:1})
insert("Bar", {1:1})
insert("Foo", {1010:5})
print(dict(d))
print([[key, [{k:v} for k,v in value.items()]] for key,value in d.items()])

由于要插入的数据基于密钥,因此dict应该适合此处。 然后,您可以将其塑造为最终想要的样子,

输出:

$ python price.py
'Foo': {1010: 10101015}, 'Bar': {0: 1, 1: 1}}
[['Foo', [{1010: 10101015}]], ['Bar', [{0: 1}, {1: 1}]]]

答案 1 :(得分:1)

您可以这样做

def insert(result, key, price, quantity):
    priceDict = result.get(key, {price: 0})
    priceDict[price] += quantity
    result[key] = priceDict
    return result

result = {}
print(result) # {}
insert(result, "Foo", 1010, 10101010)
insert(result, "Bar", 0, 1)
insert(result, "Foo", 1010, 5)
print(result) # {'Foo': {1010: 10101015}, 'Bar': {0: 1}}