Is there another way to access the data from dictionary items()?

Question

Is it possible to access the data from the dictionary items() function other than the for loop with two variables as shown in this exercise?

Answer

The results from the items() function are a Python tuple data type. You can use indexing to access the elements of the tuple. For a dictionary, the key would be index 0 and the value would be index 1. The following code example shows this usage for a simple dictionary.

letters = { "A": 10, "B": 20, "C": 30, "D": 40 }

for data in letters.items():
    print(data[0])
    print(data[1])
8 Likes

thanks for the answer to this question. It helps me a lot.

2 Likes

The lessons repeatedly mention that the methods return an object, whether a key or a value. What exactly is an ‘object’?

1 Like

An object is an instance of a class. It contains attributes that are defined in the class. Think of classes as a blueprint for an object. I hope this helps.

2 Likes

I tired it, and it printed the same result as the method in the exercise.


for data in pct_women_in_occupation.items():
    print("Women make up", data[1], "percent of", str(data[0]) + "s.")

Method in exercise:

for job, pct in pct_women_in_occupation.items():
  print("Women make up", pct, "percent of", job + "s.")

Is it safe to say both methods are interchangeable?

1 Like

They would print the same thing, yes.

The .items() method returns a tuple consisting of each key-value pair. In the first loop, you’re taking this tuple and accessing its elements using indexing. In the second loop, you’re unpacking this tuple and assigning its elements to job and pct, then using these variables.

However, if you take a look at both pieces of code, which one is more readable? Which one better implies what value each object holds (e.g. data[0] vs. job)?

5 Likes

I see your point, while both can come up with the same result, it’ll be far easier to understand the code if we write it that way job as opposed to data[0].

Thank you!

1 Like

letters = { “A”: 10, “B”: 20, “C”: 30, “D”: 40 }

for letter, numb in letters.items():
print(“Word: {} = {}”.format(letter, numb))

for k, v in pct_women_in_occupation.items():
print(“Women make up”, v, “percent of”, k +“s.”)

This works, but it seems inconsistent to use a comma in v, “percent of” and an addition sign in k + “s.”

That method of printing is disjointed and convoluted. Commas and concatenation? Python gives us methods of interpolating everything into a single string. f-string is my favorite but only works on 3.5 and later. Previous to that we had str.format() and previous to that modulo formatting.

print (f"Women make up {v} percent of {k}s.")
       |               ___            ___
       f                 \            /
                         interpolation

Note that the f is outside of (before) the double quote.

4 Likes

Will look further into f-string.
Thanks for the reply!

1 Like

The same directives apply that we use with str.format(), data typing, padding, alignment, &c.

k= 'orange juice'
v = 3.50
print (f"{k:<42} {v:6.2f}")
orange juice                                 3.50

Found this link buried in my bookmarks. Not sure it is exhaustive, but it has lots of examples.

Python f-strings - The Ultimate Usage Guide-SaralGyaan

4 Likes

sorry to necro - but thank you for this link and explanation!

1 Like

Makes work so easy for me

Many thanks for this post and the explanations.

1 Like