Python Forum
Adding keys and values to a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding keys and values to a dictionary
#1
Hey Guys.

Trying to add value, key in this order to a dictionary.
Checking with the debugger it shows that index 0 is added to new_dict, and then in the second iteration, index 1 replaces index 0 and then index 2 is added correctly.

Any idea why?

course_dict = {'I': 3, 'love': 3, 'self.py!': 2}


def inverse_dict(my_dict):
    new_dict = {}
    for key, value in my_dict.items():
        new_dict.update({value: key})
       

    return new_dict

print(inverse_dict(course_dict))
Reply
#2
Keys in a dictionary are unique, but the starting values you have are not unique. So simply reversing the order of values and keys gives a key collision. What do you think should be the answer in your final dictionary if you asked it for the key 3? inverse_dict[3] == ?

If you didn't want to lose data, you could make the value a container, like a set or a list and append any conflicts together.
Reply
#3
(Nov-19-2020, 04:39 PM)bowlofred Wrote: Keys in a dictionary are unique, but the starting values you have are not unique. So simply reversing the order of values and keys gives a key collision. What do you think should be the answer in your final dictionary if you asked it for the key 3? inverse_dict[3] == ?

If you didn't want to lose data, you could make the value a container, like a set or a list and append any conflicts together.

Thanks for your quick reply.

You are right, I got the exercise wrong. It involves making a list. Ill give it a go now.

Thanks again!
Reply
#4
This is the dictionary you are trying to make:
Output:
{3:'I', 3:'love', '2':'self.py!'}
Lets see what happens if we try to create the dictionary from a literal.
inverse_dict = {3:'I', 3:'love', 2:'self.py!'}
print(inverse_dict)
Output:
{3: 'love', '2': 'self.py!'}
Hmmm, same problem.

Lets try building the dictionary step by step:
inverse_dict = {}
inverse_dict[3] = 'I'
inverse_dict[3] = 'love'
inverse_dict[2] = 'self.py!'
print(inverse_dict)
Output:
{3: 'love', '2': 'self.py!'}
Hopefully this last example makes it clear why 'love' replaces 'I' when you SET inverse_dict[3] = 'love'. The keys in a dictionary are unique. When you set the key:value in a dictionary it sets the value associated with the key. If the key does not exist the key is added.

This is a potential problem with inverting a dictionary. A dictionary does not care if the values are unique, only the keys. When you swap keys and values the dictionary will happily overwrite any duplicate values. You could make this a key error.
course_dict = {'I': 3, 'love': 3, 'self.py!': 2}

def inverse_dict(my_dict):
    new_dict = {}
    for key, value in my_dict.items():
        if value in new_dict:
            raise KeyError(f'Key {value} already exists')
        new_dict[value] = key
    return new_dict
 
print(inverse_dict(course_dict))
Output:
Traceback (most recent call last): File "...", line 14, in <module> print(inverse_dict(course_dict)) File "...", line 8, in inverse_dict raise KeyError(f'Key {value} already exists') KeyError: 'Key 3 already exists'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 796 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Printing specific values out from a dictionary mcoliver88 6 1,316 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  Adding values with reduce() function from the list of tuples kinimod 10 2,512 Jan-24-2023, 08:22 AM
Last Post: perfringo
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,695 Dec-27-2021, 03:43 AM
Last Post: noahverner1995
  Getting values from a dictionary brunolelli 5 3,516 Mar-31-2021, 11:57 PM
Last Post: snippsat
  Python dictionary with values as list to CSV Sritej26 4 2,956 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  Conceptualizing modulus. How to compare & communicate with values in a Dictionary Kaanyrvhok 7 3,903 Mar-15-2021, 05:43 PM
Last Post: Kaanyrvhok
  variables vcnt, ocnt, and mcnt adding previous values and not resetting to 0 archanut 2 1,882 Feb-12-2021, 06:56 PM
Last Post: deanhystad
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 2,651 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  extracting second values elements only in every keys in an OrderedDict glennford49 4 2,468 Nov-12-2020, 08:22 AM
Last Post: glennford49

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020