简体   繁体   中英

How can I count occurrences of sublists in a list and display them as dict

I have the next list:

lst = [["Orange", "Carrot"], ["Green", "Apple"], ["Yellow", "Banana"], ["Orange", "Pumpkin"], ["Green", "Apple"]]

How can i display them as the following dict?:

dict_sum = {'Orange': {'Carrot': 1, 'Pumpkin': 1}, 'Green': {'Apple': 2}, 'Yellow': {'Banana': 1}}

You could use a defaultdict of Counter to build the dictionary:

from collections import defaultdict, Counter

lst = [["Orange", "Carrot"], ["Green", "Apple"], ["Yellow", "Banana"], ["Orange", "Pumpkin"], ["Green", "Apple"]]

d = defaultdict(Counter)

for key, v in lst:
    d[key][v] += 1

res = {k: dict(v) for k, v in d.items()}
print(res)

Output

{'Orange': {'Carrot': 1, 'Pumpkin': 1}, 'Green': {'Apple': 2}, 'Yellow': {'Banana': 1}}
lst = [["Orange", "Carrot"], ["Green", "Apple"], ["Yellow", "Banana"], ["Orange", "Pumpkin"], ["Green", "Apple"]] dict_sum = dict() for item in lst: color = item[0] vegetable = item[1] # search in dict_sum if color not in dict_sum: dict_sum[color] = dict() # search vegetable in color if vegetable not in dict_sum[color]: dict_sum[color][vegetable] = 0 # increase count dict_sum[color][vegetable] += 1 print(dict_sum)

Not an elegant solution but you can iterate over the list and create a dictionary:

In [14]: lst = [["Orange", "Carrot"], ["Green", "Apple"], ["Yellow", "Banana"], ["Orange", "Pumpkin"], ["Green", "Apple"]]                                                        

In [15]: k = {}                                                                                                                                                                   

In [16]: for elem in lst: 
    ...:     if k.get(elem[0],None): 
    ...:         nested = k.get(elem[0]) 
    ...:         if nested.get(elem[1],None): 
    ...:             nested[elem[1]] = nested.get(elem[1])+1 
    ...:         else: 
    ...:             nested[elem[1]]=1 
    ...:     else: 
    ...:         k[elem[0]] = {elem[1]:1} 


{'Orange': {'Carrot': 1, 'Pumpkin': 1},
 'Green': {'Apple': 2},
 'Yellow': {'Banana': 1}}

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