Home >Backend Development >Python Tutorial >Introducing three methods of accessing dictionaries
Definition dictionary dic = {'a':"hello",'b':"how",'c':"you"}
Method 1:
for key in dic: print key,dic[key] print key + str(dic[key])
Result:
a hello ahello c you cyou b how bhow
Details:
print key,dic[key], followed by a comma, automatically generates a space
print key + str(dic[key]), connection Two strings , using the plus sign, output directly without commas in between
Method 2:
for (k,v) in dic.items(): print "dic[%s]="%k,v
Result:
dic[a]= hello dic[c]= you dic[b]= how
Method Three:
for k,v in dic.iteritems(): print "dic[%s]="%k,v
Result:
dic[a]= hello dic[c]= you dic[b]= how
Contrast:
items() returns a list object, while iteritems() returns an iterator object . For example:
print dic.items() #[('a', 'hello'), ('c', 'you'), ('b', 'how')] print dic.iteritems() #<dictionary-itemiterator object at 0x020E9A50>
Digging deeper: iteritor means iterator, one data item at a time, until it lasts
for i in dic.iteritems(): print i
Result:
('a', 'hello') ('c', 'you') ('b', 'how')
[Related recommendations]
1. Special recommendation: "php Programmer Toolbox" V0.1 version download
3. Basic introduction to Python items() method
4. Example of item() function in Python traversing dictionary
5. Detailed explanation of the usage of items() series functions in Python
6. The difference between iteriitems and items in sorted
The above is the detailed content of Introducing three methods of accessing dictionaries. For more information, please follow other related articles on the PHP Chinese website!