Techno Blender
Digitally Yours.

10 Most Frequently Asked Python Dictionary Questions on Stack Overflow | by Soner Yıldırım | Nov, 2022

0 39


Questions that come from real life

Photo by Towfiqu barbhuiya on Unsplash

Stack Overflow is the largest online community that constantly asks and answers questions in software, coding, data science, and many other subjects.

What I think makes it a priceless resource is that questions come from the real-life. People post questions about what they struggle with in their jobs. The answers usually come from people who experienced the same challenge and found a solution.

I wrote an article about 10 most frequently asked questions about Pandas. In this article, we will go through the 10 most frequently asked questions about Python dictionaries on Stack Overflow.

If you are learning Python for software development or creating data-oriented products, it is highly likely you will encounter some of these problems.

I have chosen the questions based on the number of votes and views on Stack Overflow as of writing this article (skipped the duplicate ones).

1. How do I merge two dictionaries in a single expression?

There are multiple ways of solving this problem. If you are using Python 3.9 or higher, you can simply use the “|” operator.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90}
c = a | b

c
# output
{'James': 95, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

The keys in a Python dictionary must be unique so if the same key exists in both dictionaries, the combined one will only have one of them.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90, "James": 100}
c = a | b

c
# output
{'James': 100, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

The value of the key James is 100, which is what we have in dictionary b. If you write the expression as “b | a”, dictionary c will have James from dictionary a.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90, "James": 100}
c = b | a

c
# output
{'Matt': 85, 'Ashely': 90, 'James': 95, 'Jane': 98}

The reason is that the expression “a | b” is a similar operation to updating dictionary a with dictionary b. Hence, in the case of having the same keys, the value will come from the last dictionary.

The “a | b” operator returns the combined dictionary but it does not alter a or b. If you need to update a dictionary using the key-value pairs in another dictionary, use the update method.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90, "James": 100}
a.update(b)

a
# output
{'James': 100, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

In the code snippet above, dictionary a is updated with dictionary b.

If you are using Python 3.5 or above, you can use the “{**a, **b}” expression, which does the same thing as “a | b”.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90, "James": 100}
c = {**a, **b}

c
# output
{'James': 100, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

2. How can I remove a key from a Python dictionary?

The first option is the del function.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}
del a["James"]

a
# output
{'Jane': 98, 'Matt': 85, 'Ashely': 90}

The del function only works if the key exists in the dictionary. Otherwise, it raises a KeyError. If you are not sure if the key exists in the dictionary, use the pop method instead but make sure to specify what to do if the key does not exist. Otherwise, the pop method will also raise a KeyError.

Unlike the del function that only removes the specified key from the dictionary, the pop method removes the key and returns its value. If the key does not exist, it returns the value we specify.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

a.pop("James", None)
# output
95

a.pop("Max", None)
# output

The second operation in the above code snippet does not return anything since Max is not a key in dictionary a. The key James has been removed from the dictionary though.

a
# output
{'Jane': 98, 'Matt': 85, 'Ashely': 90}

3. Iterating over dictionaries using for loops

If we use a for loop with a dictionary, we iterate over keys.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

for key in a:
print(key, a[key])

# output
James 95
Jane 98
Matt 85
Ashely 90

In the for loop above, we print the key and access its value using the “a[key]” expression.

We can also iterate over both keys and values using the items method.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

for key, value in a.items():
print(key, value)

# output
James 95
Jane 98
Matt 85
Ashely 90

4. How do I sort a dictionary by value?

We can use the built-in sorted function of Python for this task. If we apply it to dictionary items (i.e. key-value pairs), the items will be sorted by keys.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

sorted(a.items())
# output
[('Ashely', 90), ('James', 95), ('Jane', 98), ('Matt', 85)]

The returned data structure is a list of tuples. Each tuple contains two values. The first one is the key and the second one is its value. In order to sort by values, we need to use the key parameter of the sorted function and specify to sort by the second item in tuples.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

sorted(a.items(), key=lambda x:x[1])
# output
[('Matt', 85), ('Ashely', 90), ('James', 95), ('Jane', 98)]

If we need to have the return data structure as a dictionary, we can just use the dict constructor.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

sorted_a = dict(sorted(a.items(), key=lambda x:x[1]))

sorted_a
# output
{'Matt': 85, 'Ashely': 90, 'James': 95, 'Jane': 98}

5. How can I add new keys to a dictionary?

We can add a new key as follows:

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

a["Max"] = 100

a
# output
{'James': 95, 'Jane': 98, 'Matt': 85, 'Ashely': 90, 'Max': 100}

If the key already exists in the dictionary, its value is updated with the new value.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

a["James"] = 100

a
# output
{'James': 100, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

6. Check if a key already exists in a dictionary

We can access the keys of a dictionary using the keys method. We can then check if a given key exists in the dictionary keys as follows:

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}
keys_to_check = ["James", "Max", "Ashley"]

for key in keys_to_check:
print(key, key in a.keys())
# output
James True
Max False
Ashley False

7. How to return dictionary keys as a list in Python?

In the previous question, we learned that the keys method returns the dictionary keys. We can apply the list constructor to create a list of dictionary keys returned by the keys method.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

list(a.keys())
# output
['James', 'Jane', 'Matt', 'Ashely']

8. How can I make a dictionary from separate lists of keys and values?

This can be done using the zip function along with the dict constructor.

names = ["James", "Jane", "Matt", "Ashley"]
grades = [95, 98, 85, 90]

grades_dict = dict(zip(names, grades))

grades_dict
# output
{'James': 95, 'Jane': 98, 'Matt': 85, 'Ashley': 90}

The keys and values are matched as they appear in the lists.

9. Create a dictionary with comprehension

We can use dictionary comprehension, which is a method to create dictionaries using iterables. It is similar to a list comprehension with a slightly different syntax.

The basic structure for the list and dictionary comprehensions are as follows:

(image by author)

Let’s do an example.

words = ['data', 'science', 'machine', 'learning']
words_len_dict = {i:len(i) for i in words}

words_len_dict
# output
{'data': 4, 'science': 7, 'machine': 7, 'learning': 8}

The expression for keys is “i” which indicates the items in the words list. The expression for values is “len(i)” which calculates the number of characters in each word.

10. Creating a new dictionary in Python

We can either use the dict constructor or empty curly braces to create an empty dictionary.

# dict constructor
a = dict()
type(a)
# output
dict

# curly braces
b = {}
type(b)
# output
dict

As of writing this article, there are 181,580 questions on Stack Overflow that are tagged Python dictionary. We have learned the answers to the first 10 of this enormous list and resource.

You can become a Medium member to unlock full access to my writing, plus the rest of Medium. If you already are, don’t forget to subscribe if you’d like to get an email whenever I publish a new article.

Thank you for reading. Please let me know if you have any feedback.


Questions that come from real life

Photo by Towfiqu barbhuiya on Unsplash

Stack Overflow is the largest online community that constantly asks and answers questions in software, coding, data science, and many other subjects.

What I think makes it a priceless resource is that questions come from the real-life. People post questions about what they struggle with in their jobs. The answers usually come from people who experienced the same challenge and found a solution.

I wrote an article about 10 most frequently asked questions about Pandas. In this article, we will go through the 10 most frequently asked questions about Python dictionaries on Stack Overflow.

If you are learning Python for software development or creating data-oriented products, it is highly likely you will encounter some of these problems.

I have chosen the questions based on the number of votes and views on Stack Overflow as of writing this article (skipped the duplicate ones).

1. How do I merge two dictionaries in a single expression?

There are multiple ways of solving this problem. If you are using Python 3.9 or higher, you can simply use the “|” operator.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90}
c = a | b

c
# output
{'James': 95, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

The keys in a Python dictionary must be unique so if the same key exists in both dictionaries, the combined one will only have one of them.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90, "James": 100}
c = a | b

c
# output
{'James': 100, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

The value of the key James is 100, which is what we have in dictionary b. If you write the expression as “b | a”, dictionary c will have James from dictionary a.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90, "James": 100}
c = b | a

c
# output
{'Matt': 85, 'Ashely': 90, 'James': 95, 'Jane': 98}

The reason is that the expression “a | b” is a similar operation to updating dictionary a with dictionary b. Hence, in the case of having the same keys, the value will come from the last dictionary.

The “a | b” operator returns the combined dictionary but it does not alter a or b. If you need to update a dictionary using the key-value pairs in another dictionary, use the update method.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90, "James": 100}
a.update(b)

a
# output
{'James': 100, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

In the code snippet above, dictionary a is updated with dictionary b.

If you are using Python 3.5 or above, you can use the “{**a, **b}” expression, which does the same thing as “a | b”.

a = {"James": 95, "Jane": 98}
b = {"Matt": 85, "Ashely": 90, "James": 100}
c = {**a, **b}

c
# output
{'James': 100, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

2. How can I remove a key from a Python dictionary?

The first option is the del function.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}
del a["James"]

a
# output
{'Jane': 98, 'Matt': 85, 'Ashely': 90}

The del function only works if the key exists in the dictionary. Otherwise, it raises a KeyError. If you are not sure if the key exists in the dictionary, use the pop method instead but make sure to specify what to do if the key does not exist. Otherwise, the pop method will also raise a KeyError.

Unlike the del function that only removes the specified key from the dictionary, the pop method removes the key and returns its value. If the key does not exist, it returns the value we specify.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

a.pop("James", None)
# output
95

a.pop("Max", None)
# output

The second operation in the above code snippet does not return anything since Max is not a key in dictionary a. The key James has been removed from the dictionary though.

a
# output
{'Jane': 98, 'Matt': 85, 'Ashely': 90}

3. Iterating over dictionaries using for loops

If we use a for loop with a dictionary, we iterate over keys.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

for key in a:
print(key, a[key])

# output
James 95
Jane 98
Matt 85
Ashely 90

In the for loop above, we print the key and access its value using the “a[key]” expression.

We can also iterate over both keys and values using the items method.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

for key, value in a.items():
print(key, value)

# output
James 95
Jane 98
Matt 85
Ashely 90

4. How do I sort a dictionary by value?

We can use the built-in sorted function of Python for this task. If we apply it to dictionary items (i.e. key-value pairs), the items will be sorted by keys.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

sorted(a.items())
# output
[('Ashely', 90), ('James', 95), ('Jane', 98), ('Matt', 85)]

The returned data structure is a list of tuples. Each tuple contains two values. The first one is the key and the second one is its value. In order to sort by values, we need to use the key parameter of the sorted function and specify to sort by the second item in tuples.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

sorted(a.items(), key=lambda x:x[1])
# output
[('Matt', 85), ('Ashely', 90), ('James', 95), ('Jane', 98)]

If we need to have the return data structure as a dictionary, we can just use the dict constructor.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

sorted_a = dict(sorted(a.items(), key=lambda x:x[1]))

sorted_a
# output
{'Matt': 85, 'Ashely': 90, 'James': 95, 'Jane': 98}

5. How can I add new keys to a dictionary?

We can add a new key as follows:

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

a["Max"] = 100

a
# output
{'James': 95, 'Jane': 98, 'Matt': 85, 'Ashely': 90, 'Max': 100}

If the key already exists in the dictionary, its value is updated with the new value.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

a["James"] = 100

a
# output
{'James': 100, 'Jane': 98, 'Matt': 85, 'Ashely': 90}

6. Check if a key already exists in a dictionary

We can access the keys of a dictionary using the keys method. We can then check if a given key exists in the dictionary keys as follows:

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}
keys_to_check = ["James", "Max", "Ashley"]

for key in keys_to_check:
print(key, key in a.keys())
# output
James True
Max False
Ashley False

7. How to return dictionary keys as a list in Python?

In the previous question, we learned that the keys method returns the dictionary keys. We can apply the list constructor to create a list of dictionary keys returned by the keys method.

a = {"James": 95, "Jane": 98, "Matt": 85, "Ashely": 90}

list(a.keys())
# output
['James', 'Jane', 'Matt', 'Ashely']

8. How can I make a dictionary from separate lists of keys and values?

This can be done using the zip function along with the dict constructor.

names = ["James", "Jane", "Matt", "Ashley"]
grades = [95, 98, 85, 90]

grades_dict = dict(zip(names, grades))

grades_dict
# output
{'James': 95, 'Jane': 98, 'Matt': 85, 'Ashley': 90}

The keys and values are matched as they appear in the lists.

9. Create a dictionary with comprehension

We can use dictionary comprehension, which is a method to create dictionaries using iterables. It is similar to a list comprehension with a slightly different syntax.

The basic structure for the list and dictionary comprehensions are as follows:

(image by author)

Let’s do an example.

words = ['data', 'science', 'machine', 'learning']
words_len_dict = {i:len(i) for i in words}

words_len_dict
# output
{'data': 4, 'science': 7, 'machine': 7, 'learning': 8}

The expression for keys is “i” which indicates the items in the words list. The expression for values is “len(i)” which calculates the number of characters in each word.

10. Creating a new dictionary in Python

We can either use the dict constructor or empty curly braces to create an empty dictionary.

# dict constructor
a = dict()
type(a)
# output
dict

# curly braces
b = {}
type(b)
# output
dict

As of writing this article, there are 181,580 questions on Stack Overflow that are tagged Python dictionary. We have learned the answers to the first 10 of this enormous list and resource.

You can become a Medium member to unlock full access to my writing, plus the rest of Medium. If you already are, don’t forget to subscribe if you’d like to get an email whenever I publish a new article.

Thank you for reading. Please let me know if you have any feedback.

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment