Home > database >  Count items from a list and append them into a dictionary if the key is in the list
Count items from a list and append them into a dictionary if the key is in the list

Time:11-14

I am trying to count items on different lists and append them in a dictionary if the items coincide with the dictionary keys but I'm struggling with the syntax and indentation, here's what I am trying to do:

# List of lists
lists = []
list_1 = (A,B,C)
list_2 = (A,A,B,B,C,C)
list_3 = (A,A,A,B,B,B,C,C,C)
lists.extend([list_1, list_2, list_2])

# Dictionary with several values
ABC_dictionary = {'A': { 'name': 'A', 'MW': 5},
                  'B': { 'name': 'A', 'MW': 6},
                  'c': { 'name': 'A', 'MW': 7},
                  'D': { 'name': 'A', 'MW': 8}}

# Get the letter count on each list
for list in lists:
    for letter, key in zip(list, ABC_dictionary.keys()): 
        if letter in ABC_dictionary.keys():
            ABC_dictionary[letter].update({'count' : 0})
            ABC_dictionary[letter]['count']  = list.count(letter)

However, this is actually making a mess and giving back counts that I don't quite get.

What I want the outcome to look like is:

#list_1
    ABC_dictionary = {'A': { 'name': 'A', 'MW': 5, 'count': 1},
                      'B': { 'name': 'A', 'MW': 6, 'count': 1},
                      'c': { 'name': 'A', 'MW': 7, 'count': 1}.
                      'D': { 'name': 'A', 'MW': 8, 'count': 0}}

#list_2
        ABC_dictionary = {'A': { 'name': 'A', 'MW': 5, 'count': 2},
                          'B': { 'name': 'A', 'MW': 6, 'count': 2},
                          'c': { 'name': 'A', 'MW': 7, 'count': 2}.
                          'D': { 'name': 'A', 'MW': 8, 'count': 0}}

#list_3
        ABC_dictionary = {'A': { 'name': 'A', 'MW': 5, 'count': 3},
                          'B': { 'name': 'A', 'MW': 6, 'count': 3},
                          'c': { 'name': 'A', 'MW': 7, 'count': 3}.
                          'D': { 'name': 'A', 'MW': 8, 'count': 0}}

For each list I will then make some other calculations for instance:

A_weight = ABC_dictionary['A']['MW'] * ABC_dictionary['A']['count']

I know that for every list the count will overwrite the previous one, so I'm also wondering if there's a way of storing the values to add them to another list.

Thank you for the help!

CodePudding user response:

Make a deep copy of ABC_dictionary for each list in lists. Then you can put all these copies into another list.

Use collections.Counter() to count the repetitions in each list.

from copy import deepcopy
from collections import Counter

results = []

for letters in lists:
    cur_dict = deepcopy(ABC_dictionary)
    letter_counts = Counter(letters)
    for letter, d in cur_dict.items()
        d['count'] = letter_counts.get(letter, 0)
    results.append(cur_dict)
  • Related