Python: Dictionary with multiple values per key

In this article, we will discuss how to create and manage a dictionary in which keys can have multiple values.


In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.

Let’s understand it by some examples,

Create a dictionary with a list as the value

# Create a dictionary where multiple values are
# associated with a key
word_freq = {'is': [1, 3, 4, 8, 10],
             'at': [3, 10, 15, 7, 9],
             'test': [5, 3, 7, 8, 1],
             'this': [2, 3, 5, 6, 11],
             'why': [10, 3, 9, 8, 12]}

In this dictionary, keys are strings, and with each key string, we have a list of numbers associated as a value field. So, basically, in this dictionary, multiple values are associated with a key.

Related Stuff,

Advertisements

Get multiple values of a key in the dictionary

When we select a key in this dictionary, it gives the value of that key. In this case, it will be a list,

# Create a dictionary where multiple
# values are associated with a key
word_freq = {'is'   : [1, 3, 4, 8, 10],
             'at'   : [3, 10, 15, 7, 9],
             'test' : [5, 3, 7, 8, 1],
             'this' : [2, 3, 5, 6, 11],
             'why'  : [10, 3, 9, 8, 12] }


# Get multiple values of a key as list
value_list = word_freq['at']

print('Values of key "at" are:')
print(value_list)

Output:

Values of key "at" are:
[3, 10, 15, 7, 9]

We selected the item from the dictionary where the key is ‘at’ and then printed all the values associated with this key.

Read More about searching contents in dictionary,

Append multiple values to a key in a dictionary

Creating a dictionary with multiple values for a key is easy, but the tricky part is appending various values for the keys.
Let’s understand by an example,

Suppose we want to add three values 20, 21, 22, for a key in the dictionary. We need to make sure that if the key already exists in the dictionary or not.

  • If yes, then append these new values to the existing values of the key.
  • If no, then and add an empty list as a value for that key and then add these values in that list.

We have created a function to do all the above mention stuff,

def add_values_in_dict(sample_dict, key, list_of_values):
    ''' Append multiple values to a key in 
        the given dictionary '''
    if key not in sample_dict:
        sample_dict[key] = list()
    sample_dict[key].extend(list_of_values)
    return sample_dict

Now let’s use this function to add multiple values for a key,

word_freq = {'is'   : [1, 3, 4, 8, 10],
             'at'   : [3, 10, 15, 7, 9],
             'test' : [5, 3, 7, 8, 1],
             'this' : [2, 3, 5, 6, 11],
             'why'  : [10, 3, 9, 8, 12] }

# Append multiple values for existing key 'at'
word_freq = add_values_in_dict(word_freq, 'at', [20, 21, 22])

print('Contents of the dictionary: ')
print(word_freq)

Output:

{'is': [1, 3, 4, 8, 10],
 'at': [3, 10, 15, 7, 9, 20, 21, 22],
 'test': [5, 3, 7, 8, 1],
 'this': [2, 3, 5, 6, 11],
 'why': [10, 3, 9, 8, 12] }

In this example, key ‘at’ already existed in the dictionary; therefore, it appended new values in the existing list of values for key ‘at’.

Example 2:

# Append multiple values for a new key 'here'
word_freq = add_values_in_dict(word_freq, 'here', [10, 11, 12])

print('Contents of the dictionary: ')
print(word_freq)

Output:

{'is': [1, 3, 4, 8, 10],
 'at': [3, 10, 15, 7, 9, 20, 21, 22],
 'test': [5, 3, 7, 8, 1],
 'this': [2, 3, 5, 6, 11],
 'why': [10, 3, 9, 8, 12],
 'here': [10, 11, 12] }

In this example, the key ‘here’ did not exist in the dictionary; therefore, it added the new key along with the supplied list of values.

Read More,

Search for value in the dictionary with multiple values for a key

Suppose we want to check if a value exists in the dictionary where multiple values are associated with a key. Then we also want to get a list of keys that contain our given value. Let’s see how to do this,

word_freq = {'is'   : [1, 3, 4, 8, 10],
             'at'   : [3, 10, 15, 7, 9],
             'test' : [5, 3, 7, 8, 1],
             'this' : [2, 3, 5, 6, 11],
             'why'  : [10, 3, 9, 8, 12] }


# Check if a value exist in dictionary with multiple value
value = 10

# Get list of keys that contains the given value
list_of_keys = [key
                for key, list_of_values in word_freq.items()
                if value in list_of_values]

if list_of_keys:
    print(list_of_keys)
else:
    print('Value does not exist in the dictionary')

Output:

['is', 'at', 'why']

Using list comprehension, we iterated over all the key-value pairs in the dictionary. For each pair, we check if the given value exists in the list of values associated with this key or not. If yes, then put that key in a separate list tracked by list comprehension. Finally, we got the list of keys that contain the value 10.

Conclusion:

So, this how we can associate multiple values with a key in the dictionary. Similarly, for other operations like searching and deleting elements from this kind of dictionary, we need to make sure that it handles the fact that values in the dictionary are lists object and contains multiple values.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top