Python Forum
Not understanding dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Not understanding dictionaries
#1
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)
Reply
#2
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
Reply
#3
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
Reply
#4
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) ?
Reply
#5
(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)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help in understanding scope of dictionaries and lists passed to recursive functions barles 2 3,212 Aug-11-2018, 06:45 PM
Last Post: barles

Forum Jump:

User Panel Messages

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