Reputation: 1026
I have seen many examples where there is required some mapping from number to word, or the opposite direction.
In my case I want to do mapping from a range of values to words
I have a dictionary intelligence = {"John" : 100 , "Mike" : 80, "Peter" : 150}
I use this function:
a = list()
for name,iq in intelligence.items():
if iq<=100:
smartness = "low iq"
a.append((name,iq),smartness ))
elif c>=100 and c<=95:
smartness = "mid"
a.append((name,iq),smartness ))
else:
smartness = "high"
a.append((name,iq),smartness ))
print a
as you can see the code is a bit redundant, any more pythonic way to achieve this result? Ore maybe a completely different approach that is better?
After the EDIT
a = list()
for name,iq in intelligence.items():
if iq<=100:
smartness = "low iq"
elif c>=100 and c<=95:
smartness = "mid"
else:
smartness = "high"
a.append((name,iq),smartness ))
print a
Upvotes: 0
Views: 40
Reputation: 11396
def iq_to_distance(iq):
if iq<=95: return "low"
if iq<=100: return "mid"
return "high"
for name,iq in intelligence.items():
print {'name': name, 'iq': iq, 'distance': iq_to_distance(iq)}
output:
{'iq': 80, 'distance': 'low', 'name': 'Mike'}
{'iq': 100, 'distance': 'mid', 'name': 'John'}
{'iq': 150, 'distance': 'high', 'name': 'Peter'}
note that I've changed the numbers a little because elif c>=100 and c<=95:
will always be False.
or one liner:
[{'name': name,
'iq': iq,
'distance': iq<=95 and "low" or iq<=100 and "mid" or "high"}
for name,iq in intelligence.items()]
output:
[{'iq': 80, 'distance': 'low', 'name': 'Mike'},
{'iq': 100, 'distance': 'mid', 'name': 'John'},
{'iq': 150, 'distance': 'high', 'name': 'Peter'}]
Upvotes: 2