Python Introducing Dictionaries Iterating and Packing with Dictionaries Unpacking with Dictionaries

Unpacking dictionaries

Can someone explain unpacking dictionaries in some details. I don't understand how I can get both keys and values. Calling the function with print_teacher(**teacher) only returns values. How can i get keys as well

4 Answers

Parker Higgins
Parker Higgins
6,276 Points

When you call print_teacher(**teacher), the **teacher is unpacking the dictionary, and turning it's contents into keyword argument:value pairs. It creates a keyword argument for each pair, with the name of the argument being the key, and the value being the value. Since you created def print_teacher(name, job, topic): you already know what all the keyword names are, they are name, job, topic.

jhon white
jhon white
19,953 Points
teacher = {
  'name':'Ashley',
  'job':'Instructor',
  'topic':'Python'
}

def print_teacher(name, job, topic):
    print(name)
    print(job)
    print(topic)


# when you pass the keyword (**"dic name")to a function, it unpack the dic to (key, value )
#like ('name':'Ashley') and assign it to the function parameter.
print_teacher(**teacher) 

Good luck :)

Thanks for your reply. When I called the function - print_teacher(**teacher) - I didn't return a key, value pair. it only returned the values? How will I get the keys?

jhon white
jhon white
19,953 Points

Because of the values been assigned to your function parameters.

if you wanna get the key and the value pair, you can use this method:

teacher = {
  'name':'Ashley',
  'job':'Instructor',
  'topic':'Python'
}

def print_teacher(dict):
    for key in dict: 
       print("key:", key, ", Value:", dict[key]) 



print_teacher(teacher) 

Good luck :)