Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 476
UpCat Avatar asked Sep 02 '11 15:09

UpCat


People also ask

Does Python support associative arrays?

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.

Are associative arrays same as dictionaries?

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.

What is difference between numeric array and associative array?

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.

How do you loop an associative array?

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.


2 Answers

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)
like image 53
Shawn Chin Avatar answered Oct 20 '22 04:10

Shawn Chin


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
like image 44
Lie Ryan Avatar answered Oct 20 '22 05:10

Lie Ryan