Extract n top elements from dictionary [duplicate] - python

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

Related

How to get the key from only the value? [duplicate]

This question already has answers here:
Getting key with maximum value in dictionary?
(29 answers)
Closed 1 year ago.
I have this dictionary:
a_dict = {"car":5,"laptop":17,"telephone":3,"photo":14}
I would like to print the key which has the highest value.
For example, I would like to print out the key laptop because it has the highest number
I have tried this so far:
def get_oldest(things):
new_list = []
for elements in things:
new_list.append(things[element])
new_list.sort()
Now, I have sorted the list from the smallest to the highest, so I know that the last item in the list has the highest value, but how do I match that to the correct key and print that.
There is a much easier way:
a_dict = {"car": 5,"laptop": 17,"telephone": 3,"photo": 14}
oldest = max(a_dict, key=a_dict.get)
# "laptop"
This uses max with a key function. You can use max on the plain dict because iterating a dict produces its keys.

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 the occurrences of the elements in list [duplicate]

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.

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]

initialize dict with keys,values from two list [duplicate]

This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 4 years ago.
I have read this link
But how do I initialize the dictionary as well ?
say two list
keys = ['a','b','c','d']
values = [1,2,3,4]
dict = {}
I want initialize dict with keys & values
d = dict(zip(keys, values))
(Please don't call your dict dict, that's a built-in name.)
In Python 2.7 and python 3, you can also make a dictionary comprehension
d = {key:value for key, value in zip(keys, values)}
Although a little verbose, I found it more clear, as you clearly see the relationship.

Categories