Create a dictionary with comprehension

Can I use list comprehension syntax to create a dictionary? For example, by iterating over pairs of keys and values: d = {… for k, v in zip(keys, values)} 1 17 Use a dict comprehension (Python 2.7 and later): {key: value for (key, value) in iterable} Alternatively for simpler cases or earlier version of Python, … Read more

How do I convert two lists into a dictionary?

I want to combine these: keys = [‘name’, ‘age’, ‘food’] values = [‘Monty’, 42, ‘spam’] Into a single dictionary: {‘name’: ‘Monty’, ‘age’: 42, ‘food’: ‘spam’} 1 18 Use zip to create a list of (key, value) tuples, then apply the dict constructor: keys = [‘a’, ‘b’, ‘c’] values = [1, 2, 3] dictionary = dict(zip(keys, … Read more

How do I sort a list of dictionaries by a value of the dictionary?

I have a list of dictionaries and want each item to be sorted by a specific value. Take into consideration the list: [{‘name’:’Homer’, ‘age’:39}, {‘name’:’Bart’, ‘age’:10}] When sorted by name, it should become: [{‘name’:’Bart’, ‘age’:10}, {‘name’:’Homer’, ‘age’:39}] 1 18