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
  Getting values from a dictionary brunolelli 5 953 Mar-31-2021, 11:57 PM
Last Post: snippsat
  Python dictionary with values as list to CSV Sritej26 4 789 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  Conceptualizing modulus. How to compare & communicate with values in a Dictionary Kaanyrvhok 7 1,107 Mar-15-2021, 05:43 PM
Last Post: Kaanyrvhok
  variables vcnt, ocnt, and mcnt adding previous values and not resetting to 0 archanut 2 482 Feb-12-2021, 06:56 PM
Last Post: deanhystad
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 693 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  extracting second values elements only in every keys in an OrderedDict glennford49 4 732 Nov-12-2020, 08:22 AM
Last Post: glennford49
  In this dictionary all the values end up the same. How? Pedroski55 2 602 Oct-29-2020, 12:32 AM
Last Post: Pedroski55
  Counting the values ​​in the dictionary Inkanus 7 1,158 Oct-26-2020, 01:28 PM
Last Post: Inkanus
  How to make a list of values from a dictionary list? faryad13 2 743 Sep-03-2020, 03:45 PM
Last Post: faryad13
  access dictionary with keys from another and write values to list redminote4dd 6 1,269 Jun-03-2020, 05:20 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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