Delete an element from a dictionary

The del statement removes an element: del d[key] Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary: def removekey(d, key): r = dict(d) del r[key] return r The … Read more

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

The sorted() function takes a key= parameter newlist = sorted(list_to_be_sorted, key=lambda d: d[‘name’]) Alternatively, you can use operator.itemgetter instead of defining the function yourself from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’)) For completeness, add reverse=True to sort in descending order newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’), reverse=True)

How can I remove a key from a Python dictionary?

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop(): my_dict.pop(‘key’, None) This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop(‘key’)) and key does not exist, a KeyError is raised. To delete a key … Read more

How can I add new keys to a dictionary?

You create a new key/value pair on a dictionary by assigning a value to that key d = {‘key’: ‘value’} print(d) # {‘key’: ‘value’} d[‘mynewkey’] = ‘mynewvalue’ print(d) # {‘key’: ‘value’, ‘mynewkey’: ‘mynewvalue’} If the key doesn’t exist, it’s added and points to that value. If it exists, the current value it points to is … Read more