Quick actions

cmd+k|ctrl+k

Navigation

Languages

Dictionaries 30/03

Snippet info

Language

Python

Visibility

public

Author

jjohn73

Created

2026-03-30T14:58:57.913472Z

Updated

2026-03-30T14:59:53.664292Z

# Dictionary
# dict - data type but also data structure, a way to organise data
# #dictionary = {
#     'a': 1,
#     'b': 2
# }

# print(dictionary['b']) # will go to b and grab the value, 2

# unordered key:value pair - in larger amounts the data may not be ordered as expected - ordered now in 3.7

# dictionary = {
#     'a': [1,2,3],
#     'b': 'hello',
#     'x': True
# }

# print(dictionary['b'])

# list vs dictionary - lists tend to be sorted, dict less often
# dictionaries can hold more information, while a list has the index and value only
# dictionary holds keys and values, leading to more info available to store/hold

# Dictionary Keys

# Dictionary keys require special property - Immutability
# For example, a number/string is acceptable, but a list is not as it can be changed

# Most of the time a key for a dictionary will be descriptive
# a key in a dictionary must be unique - repeated versions of a key will overwrite with new data
# e.g. two values with a key of '123' will prioritize the second version for an action like print

# Dictionary Methods

user = {
    'basket': [1,2,3],
    'greet': 'hello',
    'age': 20
}

# print(user.get('age')) #user.get is a method to find if the value exists in the dictionary, here we get "None" returned
# # this saves from errors occuring and stopping processes

# user2 = dict(name= 'JohnJohn')# basic form of creating a dictionary but not very common
# print(user.get('age', 55)) # by adding a value after the key, this provides a "default" answer to output if none exists
# print(user2) # prints the user2 dictionary

# print('goop' in user) # in checks if a key is within a variable, True or False
# print(20 in user.values())# user.keys and user.values allow to check if exists in those regions
# print(user.items()) # this will print the entire set of items in the dictionary for the variable
# print(user.clear()) # prints an empty dictionary - clear removes all items from dictionary
# user2 = user.copy() # duplicates the dictionaries
# print(user.clear()) # this will only clear the first user data, leaving user 2 with the original data
# print(user2)

# print(user.pop('age')) # returns value of whatever has been removed
# print(user) # the value will not be present when printing
# popitem - will remove the last key:value pair inserted in dictionary as of 3.7

# print(user.update({'age': 55})) # simply updates the value of the key, or adds a new key if not previously existing
# print(user)







INFO