Ads by ProfitSence
Close

Using Dictionary Comprehension With sorted(),Counter Method

Last Updated on Wednesday 5th Oct 2022
  • Dictionary Comprehension is a concise and memory-efficient way to create and initialize dictionaries in one line of Python code.
  • It consists of two parts: expression and context.
  • The expression defines how to map keys to values.
  • The context loops over an iterable using a single-line for loop and defines which (key, value) pairs to include in the new dictionary.
			
					frameworks = {
  'VueJS': 2,
  'AngularJS': 4,
  'Ember': 5,
  'ReactJS': 1,
  'Svelte': 3
}

print({k: v for k, v in sorted(frameworks.items(), key=lambda item: item[1])})

			
	

Output

			
					{ 'ReactJS': 1, 'VueJS': 2 ,'Svelte': 3 , 'AngularJS': 4, 'Ember': 5  }

			
	

python sort dictionary by value

Using Counter Method

  • Counter is a dictionary subclass that is used for counting hashable objects.
  • Since the values we are using are integers, we can use the Counter class to sort them.
  • The Counter class has to be imported from the collections module.
			
					from collections import Counter

frameworks = {
  'VueJS': 2,
  'AngularJS': 4,
  'Ember': 5,
  'ReactJS': 1,
  'Svelte': 3
}

count = dict(Counter(frameworks).most_common())
print(count)

			
	

Output

			
					{ 'ReactJS': 1, 'VueJS': 2 ,'Svelte': 3 , 'AngularJS': 4, 'Ember': 5  }

			
	

the method most_common() has been used to return all elements in the Counter.