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 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?
Associative arrays consist - like dictionaries of (key, value) pairs, such that each possible key appears at most once in the collection. Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any type of Python data.
A dictionary (also known as an associative array in some programming languages), is a collection of key-value pairs where each unique key maps onto a value.
Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion. Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With