About the dictionary traversing keys that you understand this particular method

Common way to traverse the dictionary key

Introduced

Let's look at the following code:

dic = {'apple': '1','orange':'2','banana':'3'}
for i in dic:
    print(i)

It will loop through output dictionary keys, that is, apple, orange, banana;

Two common ways to get the dictionary key

What if we want to get the value of the dictionary to traverse it?
It is easy to think of the following first way:
① get value from key
we know that code above will get the dictionary keys, so it is easy to think of the following ways:

dic = {'apple': '1', 'orange': '2', 'banana': '3'}
for i in dic:
    print(i, ':', dic[i])

Then the next we introduce a second way:
② method according to values:

dic = {'apple': '1', 'orange': '2', 'banana': '3'}
for i in dic.values():
    print(i)

.

items () method

Of course, the main purpose of my article is the record I learned today of the dictionary items () function
description of the items online () is given by:
Python dictionary items () method can return a list traversal (key, value) tuples array.
Usage:
① does not require any parameter to
② Return Value: returns a list form may traverse the (key, value) tuples array.
dict.item()
We tested it in python which:

dic = {'apple': '1','orange':'2','banana':'3'}
print(dic.items())
输出结果为
dict_items([('apple', '1'), ('orange', '2'), ('banana', '3')])

Ah ha, returns a list of really, so we naturally can get their keys with a for loop

for i in dic.items():
	print(i)
# 输出结果为:
('apple', '1')
('orange', '2')
('banana', '3')

However, if we are alone we like to get their keys and values it?
So let's take a look at the code above each output the result in the end is what type
type(i)
finally get the results <class 'tuple'>, and we really think the same is a tuple, then we can be like this gave its key strategy!

dic = {'apple': '1', 'orange': '2', 'banana': '3'}
print(dic.items())
for i, j in dic.items():
    print(i, ':', j)

carry out! ! ! And learn new things, yeah! ! ! Keep up! ! !

Published 82 original articles · won praise 235 · Views 1.08 million +

Guess you like

Origin blog.csdn.net/solitudi/article/details/104882697