Count the occurrences of the elements in list [duplicate] - python

This question already has answers here:
How do I count the occurrences of a list item?
(29 answers)
Closed 7 years ago.
I want to make a function that get a list, like:
['comp1', 'comp2', 'comp1', 'mycomp', 'mycomp']
And return a dictionary that the key's is the name of the computers and the values is how many times the same name\key's repeated in the list.
Like if the list get input:
["computer17", "computer6", "comp", "computer17"]
So the return is:
["computer17":"2",...]

The easiest to way to count the items in a list is using a Counter object (Counter is a child-class of the built in dictionary):
>>> from collections import Counter
>>> computers = ['computer17', 'computer6', 'comps', 'computer17']
>>> Counter(computers)
Counter({'computer17': 2, 'comps': 1, 'computer6': 1})
Excerpt from the docs:
class Counter(__builtin__.dict)
Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.

Related

Search dictionary values for an element [duplicate]

This question already has answers here:
Convert a python dict to a string and back
(12 answers)
Closed 3 years ago.
I have a predefined dictionary, and I want to be able to search the keys and values of the dictionary for a target string.
For example, if this is my dictionary:
my_dict = {u'GroupName': 'yeahyeahyeah', u'GroupId': 'sg-123456'}
I want to be check whether 'yeahyeahyeah' or 'GroupId' are in the keys or values of the dictionary. I think I want to convert the entire dictionary into a string, so that I can just do a substring search, but am open to other ideas.
EDIT: taking advice from comments
Here's how to create a list from the key value pairs in your dictionary.
my_dict = [{u'GroupName': 'yeahyeahyeah', u'GroupId': 'sg-123456'}]
my_list = list(my_dict[0].keys()) + list(my_dict[0].values())
This returns:
['GroupName', 'yeahyeahyeah', 'GroupId', 'sg-123456']

count an element in a list with list inside in python [duplicate]

This question already has answers here:
Nested List and count()
(8 answers)
Closed 4 years ago.
I have a list with one list inside and I would like to count how many times is one element repeat. for example:
list = ['a','b','c',['a','d']]
find = 'a'
list.count(find)
The ouptput is 1, but I'm looking for 2.
There is any easy way to do it?
thanks
Archive with chain.from_iterable
from itertools import chain
print(list(chain.from_iterable(lst)).count('a'))
First make your list flatten and get the count.

Extract n top elements from dictionary [duplicate]

This question already has answers here:
5 maximum values in a python dictionary
(5 answers)
Closed 4 years ago.
I have created a dictionary in python. I have sorted the dictionary with the following instruction.
dict = {}
dict[identifier] = dst
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))
print sorted_dict
Here identifier is key and dst is a value
I want to retrieve first N elements from the dictionary. How I can do that?
Use slicing to extract n elements of the list
>>> print(sorted_dict[:n])
collectons.Counter It's the way to go:
from collections import Counter
count_dict = Counter(the_dict)
print(count_dict.most_common(n))
Here you have a live example

Getting the most common key value in a list of dictionaries [duplicate]

This question already has an answer here:
python: get the most frequent value in a list of dictionaries
(1 answer)
Closed 7 years ago.
For example,
I have
myList = [{'imdb' : '12345'...}, {'imdb' : '54234'....}, {'imdb' : '12345'...}...]
I want
myList = [{'imdb' : '12345'...}, {'imdb' : '12345'...}...]
I want to get the most common imdb key value.
Thanks.
There is one question which answers how to get the most common list item, but I want the most common key value of dictionaries in a list.
This is sort of different.
from collections import Counter
most_common_imdb_value = Counter(d['imdb'] for d in myList).most_common(1)[0]
If you then need a list of those dictionaries that match the most common imdb value do:
[d for d in myList if d['imdb'] == most_common_imdb_value]

Strange behaviour when appending items to lists inside dictionaries in python [duplicate]

This question already has answers here:
Dictionary creation with fromkeys and mutable objects. A surprise [duplicate]
(3 answers)
Closed 8 years ago.
I have a dictionary indexed by 201 integer keys (0..200). the value for each of these keys is a list. generated with the code below:
dictionary=dict.fromkeys(range201,[])
i am getting this strange behaviour when i try to append items to the list belonging to one specific index, if i do this:
dictionary[1].append("foo")
i would expect this:
>>dictionary
{0:[], 1:["foo"],2:[],...}
but instead i end up with this:
>>dictionary
{0:["foo"], 1:["foo"],2:["foo"],...}
to clarify a bit the context in which the operation is performed, i am enumerating a list of values that can be None or float, i want to skip the None and append the float to the list corresponding to the enumerate index:
for i, value in enumerate(valuesList):
if value is None:
continue
dictionary[i].append(value)
this is behaviour is independent of which integer index i use, and i end up with the same values at all indices. I could use a list of lists and achieve the same result i think. but i wanted to understand this behaviour.
This is the normal behavior. All the entry of your dictionary where initialized with a reference to the same list. So when appending an element using one key, as all the key are pointing the same list, the modification is applied to all the entries of the dic.
Try this instead :
dictionary={}
for i in range(201):
#the loop make the list.__init__() (i.e. the []) being called 200 times
dictionary[i] = []
dictionary[1].append("foo")
print dictionary

Categories