Some python snippets that can be useful. I have come up with some requirements in my scripts and searched for the solutions. The working ones are kept here for reference.
Here is the snippet for it
This will display the count as 2.
This snipped does exactly that:
the sortedKeyList is the list of keys of dictionary where the keys are sorted based on values of the dictionary
Counting based on condition of dictionary values.
Lets say we have a dictionary with some keys and values like this:{ 'a' : 'hello', 'b' : 'world, 'c' : 'hello', 'd' : 'junk' }Now if you want to count number of keys that has values as "hello"
Here is the snippet for it
count = sum(1 for x in dict.values() if x =='hello')
This will display the count as 2.
Returning keys of dictionary of sorted values.
Sometimes we have to sort the dictionary with values. I have to get the list of keys in sorted order of values.This snipped does exactly that:
sortedKeyList = sorted(dict,key=dict.get, reverse=True)
the sortedKeyList is the list of keys of dictionary where the keys are sorted based on values of the dictionary
Comments
Post a Comment