website creator Keys for dictionaries have to be immutable types. This is to ensure that the key can be converted to a constant hash value for quick look-ups. Immutable types include integer, floats, strings, tuples.
empty_dict = {} person = {'name': 'Alex', 'age': 35, 'pets': ['cat', 'dog'], 7: 'Seven'} print(person['name']) # Alex (will throw an error if does not exist) print(person[7]) # Seven print(person.get('name')) # Alex print(person.get('phone')) # None (does not throw a KeyError error) print(person.get('phone', '911')) # 911 (return a default value if does not exist) person['phone'] = '555-7777' print('Update dict:') person.update({'name': 'Lisa', 'email': 't@t.com'}) print(person['name']) # Lisa print('Remove key and its value in the dict:') phone = person.pop('phone') print(phone) # 555-7777 print(person.get('phone')) # None print('Delete key and its value in the dict:') del person[7] del person['pets'] print(person) # {'name': 'Lisa', 'age': 35, 'email': 't@t.com'} print('Get number of keys in the dict:') print(len(person)) # 3 print('Get list of keys and list of values:') print(list(person.keys())) # ['name', 'age', 'email'] print(list(person.values())) # ['Lisa', 35, 't@t.com'] print(person.items()) # dict_items([('name', 'Lisa'), ('age', 35), ('email', 't@t.com')]) print('Loop thru keys in the dict:') for key in person: print(key) print('Loop thru keys and values in the dict:') for key, value in person.items(): print(key, value) print('Check if key exist in the dict:') print('name' in person) # True print('Set key-value if it does not exist yet:') person.setdefault('country', 'Canada') print(person.get('country')) # Canada person.setdefault('country', 'France') print(person.get('country')) # Canada
Dictionary comprehension
names = ['Bruce Wayne','Peter Parker', 'Wade Wilson'] heroes = ['Batman', 'Spiderman', 'Deadpool'] # create dictionary using dictionary comprehension my_dict = {name: hero for name, hero in zip(names, heroes)} print(my_dict) # {'Bruce Wayne': 'Batman', 'Peter Parker': 'Spiderman', 'Wade Wilson': 'Deadpool'} # create dictionary using dictionary comprehension with if condition my_dict2 = {name: hero for name, hero in zip(names, heroes) if hero!='Deadpool'} print(my_dict2) # {'Bruce Wayne': 'Batman', 'Peter Parker': 'Spiderman'}