简体   繁体   中英

Group similar list elements into dict without grouping it's multiple occurence

I have a huge list where I convert it to a dict(based on 1st list element) for quick search with key.

List:

[0100,A,1.00,1]
.
.
[0450,A,1.00,1]
[0470,B,1.00,1]
[0480,A,1.00,1]
[0490,A,1.00,1]
[0500,A,1.00,1] #list-1 for below ref
[0510,B,1.00,1]
[0520,A,1.00,1]
[0530,A,1.00,1]
[0500,A,1.00,1] #list-2 for below ref
[0510,B,1.00,1]
[0520,X,1.00,1] #........

Converting into Dic:

for key, *vals in bytes_data: #Probably need a diff approach here itself instead appending
    data_dict.setdefault(key, []).append(vals) 

Dict looks like

{
    '0450': [[A,1.00,1]],
    '0470': [[B,1.00,1]],
    '0480': [[A,1.00,1]], #......
}

Now, my current scenario needs to chunk data like 4xx/5xx/... based on situations. For which, I use..

key_series = ["0" + str(x) for x in range(500, 600, 10)]
article_data = {
    key: data_dict[key] for key in set(key_series) & set(data_dict)
}

The issue is, for some series like 5xx there are multiple occurrences. In that case My dict is grouped like

{
    0500: [list-1,list-2,..],
    0510: [list-1,list-2,..]
}

But, I need something like

{
0500-1: {0500: [list-1], 0510: [list-1],....}, 
0500-2: {0500: [list-2], 0510: [list-2],....},
}

Any trick to achieve this ? Thanks.

Not sure, if this is what you want, letme know if this solves your problem

from collections import defaultdict
data_dict = {
    "0500": [["A",1.00,1]],
    "0510": [["A",1.00,1], ["B",1.00,1], ["B",1.00,1]],
    "0520": [["A",1.00,1], ["D",1.00,1]]
}
key_series = ["0" + str(x) for x in range(500, 600, 10)]
article_data = {
    key: data_dict[key] for key in set(key_series) & set(data_dict)
}
res = defaultdict(dict)
for k ,v in data_dict.items():
    for i, d in enumerate(v):
        # for now 0500 is hardcoded, which can be made dynamic as per requirement
        res[f"0500-{i+1}"][k] = d

print(res)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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