Python traversal of the dictionary, take a note

Iterating over the dictionary

d = {'x': 1, 'y': 2, 'z': 3}

Traverse keys

for key in d:
    print key,
y x z
for key in d.iterkeys():
    # d.iterkeys(): an iterator over the keys of d
    print key,
y x z
for key in d.keys():
    # d.keys() -> ['y', 'x', 'z']
    print key,
y x z

Iterate over values

for value in d.itervalues():
    # d.itervalues: an iterator over the values of d
    print value,
》》2 1 3
for value in d.values():
    # d.values() -> [2, 1, 3]
    print value,
>>2 1 3

Traverse keys and values

for key, value in d.iteritems():
    # d.iteritems: an iterator over the (key, value) items
    print key,'corresponds to',d[key]
y corresponds to 2
x corresponds to 1
z corresponds to 3
for key, value in d.items():
    # d.items(): list of d's (key, value) pairs, as 2-tuples
    # [('y', 2), ('x', 1), ('z', 3)]
    print key,'corresponds to',value
y corresponds to 2
x corresponds to 1
z corresponds to 3

PART2

  • Use the for statement to traverse the key value in the dictionary, and get the corresponding content value through the key value

# -*- coding:utf-8 -*-

dict={"a":"Alice","b":"Bruce","J":"Jack"}

# 实例一:
for i in dict:
    print "dict[%s]=" % i,dict[i]

结果:
#dict[a]= Alice
# dict[J]= Jack
# dict[b]= Bruce


# 实例二:
for i in  dict.items():
    print i

结果:
# ('a', 'Alice')
# ('J', 'Jack')
# ('b', 'Bruce')

# 实例三:
for (k,v) in  dict.items():
    print "dict[%s]=" % k,v

结果:
# dict[a]= Alice
# dict[J]= Jack
# dict[b]= Bruce

# 实例四:
for k,v in dict.iteritems():
        print "dict[%s]=" % k,v

结果:
# dict[a]= Alice
# dict[J]= Jack
# dict[b]= Bruce

# 实例五:
for (k,v) in zip(dict.iterkeys(),dict.itervalues()):
        print "dict[%s]=" % k,v

结果:
# dict[a]= Alice
# dict[J]= Jack
# dict[b]= Bruce
  • Note: The value of the dictionary in the traversal can be guaranteed, but the order is uncertain. If order is required, keyword ordering can be proposed.

 

Guess you like

Origin blog.csdn.net/weixin_40244676/article/details/102649795