Menu Close

Dictionaries

The main difference between dictionaries and lists or tuples is the indexes. While tuples and lists use only predetermined integer indexes, dictionaries can have custom indexes. This makes them extremely useful for well-organized databases and is fundamental for good python programming.

Declaration

The declaration of python dictionaries is similar to that of lists and tuples. However, the main difference is that for each value inside a dictionary, it also needs a complementary key element. The syntax of a dictionary is braces “{}”, and each value is separated using commas. Each dictionary entry has a value and a key, separated by a colon.

Example 1:

User1 = {“Name” : “John Green”, “Age” : 32, “Occupation” : “Programmer”}ombining 
User2 = {“Name” : “Emma Summers”, “Age” : 26, “Occupation” : “Accountant”}

Values in dictionaries can be accessed by the key, with similar syntax to lists. They are accessed using brackets “[key]”.

Example 2:

User1 = {“Name” : “John Green”, “Age” : 32, “Occupation” : “Programmer”}
User2 = {“Name” : “Emma Summers”, “Age” : 26, “Occupation” : “Accountant”}
print(User1[“Name”])
print(User2[“Name”])

Output:

John Green
Emma Summers

Adding or modifying values in a Dictionary

Modifying values within a dictionary is very similar to modifying values in a list. By addressing a key, you can reassign it another value. It follows the same syntax as list value modification “dict[key] = value”.

Example 1:

User1 = {“Name” : “John Green”, “Age” : 32, “Occupation” : “Programmer”}

User1[“Age”] = 29
print(User1)

Output:

{‘Name’ : ‘John Green’, ‘Age’ : 29, ‘Occupation’ : ‘Programmer’}

Rather than using any add() or append() function, adding values to a dictionary is quite simple. It uses the same syntax as modifying an existing value. By assigning a key element to a value, it adds it to the dictionary. This works because dictionaries are not ordered – therefore, adding a value to the end has no issues.

Example 2:

User1 = {“Name” : “John Green”, “Age” : 32, “Occupation” : “Programmer”}

User1[“Height”] = “186cm”
print(User1)

Output:

User1 = {‘Name’ : ‘John Green’, ‘Age’ : 29, ‘Occupation’ : ‘Programmer’, ‘Height’ : ‘186cm’}

The .keys() method

The keys() method in python is used to return an object which encapsulates all the keys of a given dictionary. The syntax is “Dict.keys()”.

Example 1:

User1 = {'James': 18,'Robert':12,'Jessica':22,'Lisa':25}
print(User1.keys())

Output:

dict_keys(['James', 'Robert', 'Jessica', 'Lisa'])

This dict_keys object has little use on its own, but we’re able to work with it once we cast it into a list. Commonly, these dict_keys objects are used with the syntax “list(Dict.keys)” to make the object more useful.

Example 2:

User1 = {'James' : 18,'Robert' : 12,'Jessica' : 22,'Lisa' : 25}
KeyList = list(User1.keys())

#reversed list
KeyList.reverse()
print(“Reversed:”, KeyList)

#sorted list
KeyList.sort()
print(“Sorted:”, KeyList)

Output:

Reversed: ['Lisa', 'Jessica', 'Robert', 'James']
Sorted: ['James', 'Jessica', 'Lisa', 'Robert']

Sorting Dictionaries by Keys

Sorting dictionaries in python are more complex than sorting lists. However, there are still ways to do so.

Consider the following segment of code:

User1 = {'James': 18,'Robert':12,'Jessica':22,'Lisa':25}
keys = list(User1.keys())
keys.sort()

for key in keys:
     print(":".join((key, str(User1[key]))))

Output:

James:18
Jessica:22
Lisa:25
Robert:12

The code segment from above may look confusing or complex at first, but we can break it down:

User1 = {'James': 18,'Robert':12,'Jessica':22,'Lisa':25}
keys = list(User1.keys())
keys.sort()

This code initializes the dictionary. It contains a list of people and their age. Then, it gets the keys of the dictionary from before and casts the object into a list. It then sorts the list by alphabetical order.

for key in keys:
     print(":".join((key, str(User1[key]))))

This code contains an enhanced for loop, which gets every key in the list and returns its value. It prints out “Key:Value”. This is because we use the .join method to combine the key and its value within the dictionary.

Combining Dictionaries

There are 2 methods we can use for combining dictionaries: the update() method, or using **Kwargs (Keyword Arguments)

Consider the following scenario: Below are 2 separate dictionaries – one for male students, and one for female students. These dictionaries contain their birth year. These 2 dictionaries need to be combined into one.

MyDict = {“John” : 1997, “James” : 1989, “Michael” :1983, “William” : 2002}
FemaleDict = {“Tiffany” : 2001, “Ashley” : 1994, “Emily” : 2000, “Sarah” : 1986}

The update() method

One such solution to this problem is the update() method. The syntax for the update() method is “Dict.update(OtherDict)”. The values of the dictionary in the parentheses will be added to the end of the first.

Example:

MyDict = {"John" : 1997, "James" : 1989, "Michael" :1983, "William" : 2002}
FemaleDict = {"Tiffany" : 2001, "Ashley" : 1994, "Emily" : 2000, "Sarah" : 1986}
MyDict.update(FemaleDict)
print(MyDict)

Output:

{'John': 1997, 'James': 1989, 'Michael': 1983, 'William': 2002, 'Tiffany': 2001, 'Ashley': 1994, 'Emily': 2000, 'Sarah': 1986}

Keyword Arguments (** method)

This method only works for Python 3.5 and above. Using ** in front of a variable replaces the variable itself with all the values inside it. Because of this, we can combine 2 dictionaries into one larger dictionary.

Example:

MyDict = {"John" : 1997, "James" : 1989, "Michael" :1983, "William" : 2002}
FemaleDict = {"Tiffany" : 2001, "Ashley" : 1994, "Emily" : 2000, "Sarah" : 1986}
UserDict = {**MyDict, **FemaleDict}

print(UserDict)

Output:

{'John': 1997, 'James': 1989, 'Michael': 1983, 'William': 2002, 'Tiffany': 2001, 'Ashley': 1994, 'Emily': 2000, 'Sarah': 1986}

Membership Test:

Often programmers need to test if a given key is inside a dictionary. For this, we can use membership tests and membership operators. Using the “in” keyword, we can test if the object is present in the dictionary. The expression will return True if the key is inside the dictionary, and False otherwise.

Example:

User1 = {'James' : 18, 'Robert' : 12, 'Jessica' : 22, 'Lisa' : 25}

if “John” in User1:
     print(True)
else:
     print(False)

Output:

False
Posted in Articles, Programming Language, Python, Python, Textbook and Training Project

Related Articles

Leave a Reply

Your email address will not be published.

Leave the field below empty!