How to convert an associative array in python?
I am really new to python and I can't find any information about this. I have an associative array item
,
item['id'] = 0
item['title'] = 'python'
I want to validate the contents of item but I dont want to use 开发者_JAVA百科the index name like 'title'
but just have a for loop and iterate over all entries in item regardless of their meaning. Something like that
for a in range(0, len(item)):
print (item[a])
Any ideas or suggestions?
In Python, associative arrays are called dictionaries.
A good way to iterate through a dict is to use .iteritems()
:
for key, value in item.iteritems():
print key, value
If you only need the values, use .itervalues()
:
for value in item.itervalues():
print value
As you learn more about Python and dictionaries, take note of the difference between .iteritems()
/itervalues()
(which returns an iterator) and items()
/values()
(which returns a list (array)).
In Python 3
.iteritems()/.itervalues()
have been removed and items()/values()/keys()
return iterators on the corresponding sequences.
for key, value in item.items():
print(key)
print(value)
There are three ways to iterate a dictionary:
item = {...}
for key in item: # alternatively item.iterkeys(), or item.keys() in python 3
print key, item[key]
item = {...}
for value in item.itervalues(): # or item.values() in python 3
print value
item = {...}
for key, value in item.iteritems(): # or item.items() in python 3
print key, value
精彩评论