I have the following list:
name = ["Anne", "Jack", "Mary"]
I also have a nested list where each element is another list and is connected with the name present in the index of name
list. This is shown below:
n1 = [[0, 0, 3], [0, 5, 5], [1, 3, 3]]
So for 'Anne'
, the first element in list name
, the list from n1
connected to it is the first element [0, 0, 3]
.
Similarly, for "Jack"
, the second element in list name
, the list from n1
connected to it is the second element [0, 5, 5]
, and so forth.
I want to count the occurrence of each number in each element of n1
and connect it to the names in name
list in a dictionary format.
So I want my output to look like the below:
{'Anne': {'0': 2, '3': 1}, 'Jack': {'0': 1, '5': 2}, 'Mary': {'1': 1, '3': 2}}
I have tried the below:
from collections import Counter
clust = {}
for val in name:
clust[val] = {}
for e in n1:
wc = Counter(str(e1) for e1 in e)
clust[val] = dict(wc)
But this gives me the output:
clust = {'Anne': {'1': 1, '3': 2}, 'Jack': {'1': 1, '3': 2}, 'Mary': {'1': 1, '3': 2}}
Which is incorrect. How do I achieve the output that I want?
You need to match the data from n1
with each item in name
; the easiest way is with zip
:
>>> from collections import Counter
>>> name = ["Anne", "Jack", "Mary"]
>>> n1 = [[0,0,3], [0,5,5], [1,3,3]]
>>> {name_: Counter(data) for name_, data in zip(name, n1)}
{'Anne': Counter({0: 2, 3: 1}), 'Jack': Counter({5: 2, 0: 1}), 'Mary': Counter({3: 2, 1: 1})}
(Note the use of a "dictionary comprehension", see the docs.)
If the keys in your Counter
s being strings is crucial, you can use map
to convert the integers before counting:
>>> {name_: Counter(map(str, data)) for name_, data in zip(name, n1)}
{'Anne': Counter({'0': 2, '3': 1}), 'Jack': Counter({'5': 2, '0': 1}), 'Mary': Counter({'3': 2, '1': 1})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With