14. Can you iterate thru values of a dictionary?


#1

I'm trying to do something like this...

for key in inventory:
    print key + ": " + key[inventory]

The ultimate goal is to iterate through the list and print both the keys and values so it will print something like...

gold: 500
pouch: flint, twine, gemstone
backpack: xylophone,dagger, bedroll,bread loaf
etc.


https://www.codecademy.com/en/courses/python-beginner-en-pwmb1/2/5?curriculum_id=4f89dab3d788890003000096


#2

Did you mean to write,

print key + ": " + inventory[key]

?

key in the above is the member name, inventory[key] is the member value. Together they make up a property of the inventory dictionary object.

Segue

Python offers two tools that will let us create a list of just keys, or just values.

dictionary.keys()

dictionary.values()

Both of these return a list object.

 > my_dict = {'one': 1, 'two':2, 'three': 3}
 > my_dict.keys()
=> ['three', 'two', 'one']
 > my_dict.values()
=> [3, 2, 1]

However this is unrelated to the lesson so just add it to your tool kit. Since dictionaries are not ordered, we cannot assume that the keys() list will correspond correctly with the values() list. Bear this in mind.


#3

Many thanks @mtf I did mean to write inventory[key]

In any event. This is useful info. Thank you.


#4

This works too...

for key in inventory:
    print key + ": %s" % inventory[key]

#5

May as well go all out since you are using string formatting. No need for concatenation.

print "%s: %r" % (key, inventory[key])

#6

Hi @jaydacoder ,

Here's another approach, using a function, inventory_itemizer, to return a string in the format exemlified in your original post ...

def inventory_itemizer(inventory):
    # create sorted list of containers
    containers = inventory.keys()
    containers.sort()
    inv_str = ""
    # process each container
    for key in containers:
        inv_str += key + ":"
        if type(inventory[key]) == list:
            inventory[key].sort()
            inv_str += " " + ", ".join(inventory[key])
        else:
            inv_str += " " + str(inventory[key])
        inv_str += "\n"
    return inv_str

print(inventory_itemizer(inventory))

Output ...

backpack: bedroll, bread loaf, xylophone
burlap bag: apple, small ruby, three-toed sloth
gold: 550
pocket: lint, seashell, strange berry
pouch: flint, gemstone, twine

For a creative programmer, there's still room for improvement. :wink: For example, the alignment of the items in the output can be refined.

EDIT (July 13, 2016) - The creative programmer may also want to investigate whether or not the function alters the original object that is passed to it in any manner, including the items it contains. If it is deemed necessary, a deep copy can be created within the function. This issue should be considered when working with certain mutable objects, such as dictionaries and lists.

See Python: 8.17. copy — Shallow and deep copy operations.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.