简体   繁体   English

带条件的字典嵌套列表

[英]Nested lists with dictionaries based on condition

I feel like i'm loosing my mind over this... 我觉得我对此感到迷茫...

So I have added comments twice because i think i'm not really making sense. 因此,我两次添加了评论,因为我认为我没有任何意义。 The code I have is more psuedocode because I have been going in circles. 我拥有的代码更多是psuedocode,因为我一直在圈子里逛。

The idea is to have a list of items that have a dictionary containing various prices, with various quantity's according to that price. 这个想法是要有一个包含字典的项目清单,其中包含各种价格,并根据该价格具有不同数量。 Ideally I want to insert them in order of the name, then in order of the price 理想情况下,我想按名称顺序插入它们,然后按价格顺序插入

Here is what I have so far. 这是我到目前为止所拥有的。

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)

This should print; 这应该打印;

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

Perhaps you should use a better data structure like, 也许您应该使用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()])

Since, the data to be inserted is based on the key, a dict should be apt here. 由于要插入的数据是基于密钥的,因此此处应该使用dict And you could shape it to be however you want in the end like, 您可以将其塑造为最终想要的样子,例如,

Output: 输出:

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

You could do something like this 你可以做这样的事情

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}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM