Man utd
Man utd

Reputation: 131

Mapping list and dictionary in Python

I am trying to map values between dictionary and list in Python. I am trying to count the number of objects I found in the image: For example I found: Squares:3 Rectangles:4 Oval=2 Triangle=1

Now I append all of them to a list in descending order.

The list becomes:[4,3,2,1]

Now I somehow wanna say that '4' in the list corresponds to 'rectangle', '2' corresponds to 'Oval' I am trying to use a dictionary but struggling.

Since , I am doing this for multiple images, the output will be different. For example, the next image gives the results:

Squares:4 Rectangles:3 Oval=1 Triangle=2

Now the List becomes [4,3,1,2]

Therefore, it should map '4' to Squares and not rectangle

Upvotes: 1

Views: 192

Answers (1)

jedwards
jedwards

Reputation: 30260

I'd use a dictionary:

# Squares:3 Rectangles:4 Oval=2 Triangle=1

shapes = {}
shapes["Square"]    = 3
shapes["Rectangle"] = 4
shapes["Oval"]      = 2
shapes["Triangle"]  = 1

print(shapes)               # {'Square': 3, 'Oval': 2, 'Triangle': 1, 'Rectangle': 4}

# Sort list of key,value pairs in descending order
pairs = sorted(shapes.items(), key=lambda pair: pair[1], reverse=True)
print(pairs)                # [('Rectangle', 4), ('Square', 3), ('Oval', 2), ('Triangle', 1)]

# Get your list, in descending order
vals = [v for k,v in pairs]
print(vals)                 # [4, 3, 2, 1]

# Get the keys of that list, in the same order
keys = [k for k,v in pairs] # ['Rectangle', 'Square', 'Oval', 'Triangle']
print(keys)

Output:

{'Square': 3, 'Oval': 2, 'Triangle': 1, 'Rectangle': 4}          # shapes
[('Rectangle', 4), ('Square', 3), ('Oval', 2), ('Triangle', 1)]  # pairs
[4, 3, 2, 1]                                                     # vals
['Rectangle', 'Square', 'Oval', 'Triangle']                      # keys

For observant readers, the dictionary isn't necessary at all -- however I imagine there is more to the goal that we don't know about, where a dictionary would make the most sense.

Upvotes: 2

Related Questions