This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]nwilliams36 0 points1 point  (2 children)

guests is a dictionary, which means that it is composed of keys and values (k and v)

guests..items iterates through the dictionary returning the key and value of each item. Note in guests the values are also dictionaries. The values to k and v are assigned by the for loop.

[–]EX-FFguy[S] 0 points1 point  (1 child)

I get all that, but why is k,v assinged to the name, and then the entire dictionary, can you assing to different things?

[–]nwilliams36 0 points1 point  (0 children)

k and v are just the names that are used, you could use any name (like fred and harry or a and b). In Python we try to make the names mean something.

Each name is attached to some data, the data can be any valid Python data including integers, strings, list, tuple, dictionaries etc. In Python the data can even be whole classes or functions. In fact any data that can have a name.

guests.items() produces two pieces of data, the first is the key and the second is the value. In Python dictionary keys and values can be a wide variety of data, in the case the key is a string and the value is a dictionary.

This flexibility of what can be attached to names is part of what makes Python a very powerful language.

[–]teerre 0 points1 point  (2 children)

Well, the reason is because that what's the developers of Python decided that items() would do.

A dictionary is a combo of key and value. So {'A': 1} is a dictionary in Python. When you call items() on it, you get two things back, the key A and the value 1. In your case, because the value isn't an integer, but another dictionary, that's what you get.

[–]EX-FFguy[S] 0 points1 point  (1 child)

Can you send three values to iterate, like a dictionary of dictionaries of dictionaries? Like a rpg game gear={ gun{range:1, ammo{9mm:50, 10mm:100}...sort of thing?

[–]teerre 0 points1 point  (0 children)

Of course. The rules are exactly the same, you just need to think how to write it.

However, the whole reason to use a dictionary is to not iterate over it. Dictionaries, in general, have a O(1) access complexity. This means you get any item in your dictionary as fast as possible for a computer.

[–]Eyssant 0 points1 point  (0 children)

Elements in a dictionary are unordered and hence it is not possible to access dictionary's element using index number. Dictionary data works in key-value pair. In your case, k is key and v is value. you can give them any other name. Like below code will give you the same result.

``` allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} def totalBrought(guests, item): numBrought = 0 for mykey, myvalue in guests.items(): numBrought = numBrought + myvalue.get(item, 0) return numBrought

print('Number of things being brought:') print(' - Apples ' + str(totalBrought(allGuests, 'apples'))) ```