user7519
user7519

Reputation: 17

How to access associative arrays in Python

How to print the values in the 0 key line by line, then values in 1 key subsequently? How do we access this whole values of associative array?

glyph = {
    '0': [" ##### ", " ## ## ", "## ## ", "## ## ", "## ## ", " ## ## ", " ##### "], 
    '1': [" ## ", " #### ", " ## ", " ## ", " ## ", " ## ", " ###### "]
}

Upvotes: 0

Views: 2324

Answers (3)

rassar
rassar

Reputation: 5670

Like this:

for valuelist in glyph.values():
    for value in valuelist:
        print(value)


 ##### 
 ## ## 
## ## 
## ## 
## ## 
 ## ## 
 ##### 
 ## 
 #### 
 ## 
 ## 
 ## 
 ## 
 ###### 

To access an individual list use glyph['0'], glyph['1'], etc.

To get a list of all of the values, use list(glyph.values()).

To make them into one large list, use a list comprehension:

[i for j in glyph.values() for i in j].

Note that dictionaries are not sorted, so you may want to do something like this:

for valuelist in {key: glyph[key] for key in sorted(glyph)}:
    for value in valuelist:
        print(value)

Where {key: glyph[key] for key in sorted(glyph)} creates an inline dictionary based on a sorted version of glyph.

Or look into collections.OrderedDict if you want it to be ordered. For further reference, look up “dictionaries in python”.

Upvotes: 1

Daniel Pryden
Daniel Pryden

Reputation: 60987

Unless this is a SortedDict or other non-dict mapping structure, there is no guarantee that you will iterate in sorted order of the keys. If you care about getting the '0' values, then the '1' values, etc., you need something like this:

[x for x in glyph[y] for y in sorted(glyph.keys())]

Upvotes: 1

Rudresh Ajgaonkar
Rudresh Ajgaonkar

Reputation: 790

[y for y in [x  for x in glyph.values()]]

List Comprehension Way.

Upvotes: 0

Related Questions