Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16951

Count from a list the number of values in a key

$
0
0

I have one dictionary with keys and a list as a value. I want to create a new dictionary which will store the KEY of my_dict but as a value the count of letters that correlate with my_list. If KEY 'A' has 'A', 'B' then I want to count if I find the amount of 'A' or 'B' in my_list.

Also I would like to know how to do it in vanilla Python using nested for loops because I've seen people use:

new_dict = [my_dict[x] for x in my_list if x in my_dict]

Which I don't really understand fully. I hope I expressed myself correctly.

my_dict = {'A': ['A', 'B'], 'B': ['C', 'D'], 'C': ['E', 'F']}my_list = ['A', 'D', 'A', 'C', 'F', 'F']new_dict = {}

**Output:**

{'A': 2, 'B': 2, 'C': 2} 

Since key 'A' had as a value 'A', 'B' there was only two A's in my_list but no B's so the count is 2 and that's the value in case of confusion.

new_dict = [my_dict[x] for x in my_list if x in my_dict]

And I tried to nested for loops but I struggle with nested for loops


Viewing all articles
Browse latest Browse all 16951

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>