Categories
Python Answers

How to append multiple values for one key in a dictionary with Python?

Spread the love

Sometimes, we want to append multiple values for one key in a dictionary with Python.

In this article, we’ll look at how to append multiple values for one key in a dictionary with Python.

How to append multiple values for one key in a dictionary with Python?

To append multiple values for one key in a dictionary with Python, we can set the value for a key to a list and the append to the list.

For instance, we write

years_dict = dict()

for line in list:
    if line[0] in years_dict:
        years_dict[line[0]].append(line[1])
    else:
        years_dict[line[0]] = [line[1]]

to loop through the list list with a for loop.

In it, we check if line[0] is a key in the years_dict dict.

If it is, then we call append to append line[1] into the list.

Otherwise, we assign a list with line[1] in it as the value of the entry with key line[0].

Conclusion

To append multiple values for one key in a dictionary with Python, we can set the value for a key to a list and the append to the list.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *