Python Forum

Full Version: Not understanding dictionaries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Ok, I am reading a book automate the boring stuff, I am on the dictionaries chapter because I’m focusing on dictionaries right now maybe I should go back to for loops but,
I have a couple questions. Regarding the following code and what it is doing.
At the for loop for k,v in inventory.items() what is happening here?
At print(str(v) + ‘’ + k ) what is the ‘ ‘ empty string?
And I guess at item_total += v what is going on here as well?





stuff={
	'rope':1,'torch':6,'gold coins':45,'dagger':1,'arrow':12
}

def display_Inventory(Inventory):
	print('Inventory')
	Item_total=0
	for k,v in Inventory.items():
		print(str(v)+''+k)
		Item_total += v
		print('Total number of items:' + str(Item_total))
		
display_Inventory(stuff)
use keys to get count:
>>> stuff={
...     'rope':1,'torch':6,'gold coins':45,'dagger':1,'arrow':12
... }
>>> def display_inventory(inventory):
...     print(f"\nInventory: Total items: {len(inventory.keys())}\n")
...     for key, value in inventory.items():
...         print(f"{key}: {value}")
... 
>>> display_inventory(stuff)

Inventory: Total items: 5

rope: 1
torch: 6
gold coins: 45
dagger: 1
arrow: 12
items() returns all of the keys/values in the dictionary, one tuple at a time. So each time through the loop, k is set to one of the keys, and v to the corresponding value of that key.

>>> d = {'key': 'value', 'A': 1, 'B': 2}
>>> list(d.items())
[('key', 'value'), ('A', 1), ('B', 2)]
The empty string is probably a typo. I'd guess someone wanted a blank space between the key and the value in the print and it became empty instead of a space.

This is the form of an augmented assignment. It's basically the same thing as writing Item_total = Item_total + v
Wow!? Thanks again! I should have gotten that.

Now I still don’t seem to understand item_total += v
Is it set to the dictionaries value pairs ,added, then printed
Out by str(item_total) ?
(Jun-20-2020, 03:10 AM)gr3yali3n Wrote: [ -> ]Now I still don’t seem to understand item_total += v

this is equivalent to
item_total = item_total + v
it get printed because of the print function. you need to convert to str with str(item_total) because you can not concatenate str and int. As @Larz60+ suggested, better use formatted string literals (f-strings)