Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an element from tuple of tuples in python [duplicate]

Tags:

python

tuples

Possible Duplicate:
Tuple value by key

How do i find the country name by having its code,

COUNTRIES = (
   ('AF', _(u'Afghanistan')),
   ('AX', _(u'\xc5land Islands')),
   ('AL', _(u'Albania')),
   ('DZ', _(u'Algeria')),
   ('AS', _(u'American Samoa')),
   ('AD', _(u'Andorra')),
   ('AO', _(u'Angola')),
   ('AI', _(u'Anguilla'))
)

I have code AS, find its name without using forloop on COUNTRIES tuple?

like image 477
Ahsan Avatar asked Jan 05 '12 09:01

Ahsan


People also ask

How do you find duplicates in tuple Python?

Initial approach that can be applied is that we can iterate on each tuple and check it's count in list using count() , if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set() .

Can tuple have duplicate values Python?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

Can tuples repeat?

We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a tuple, it becomes the repetition operator. The repetition operator makes multiple copies of a tuple and joins them all together. Tuples can be created using the repetition operator, *.


2 Answers

You can simply do:

countries_dict = dict(COUNTRIES)  # Conversion to a dictionary mapping
print countries_dict['AS']

This simply creates a mapping between country abbreviations and country names. Accessing the mapping is very fast: this is probably the fastest method if you do multiple lookups, as Python's dictionary lookup is very efficient.

like image 76
Eric O Lebigot Avatar answered Sep 21 '22 20:09

Eric O Lebigot


COUNTRIES = (
   ('AF', (u'Afghanistan')),
   ('AX', (u'\xc5land Islands')),
   ('AL', (u'Albania')),
   ('DZ', (u'Algeria')),
   ('AS', (u'American Samoa')),
   ('AD', (u'Andorra')),
   ('AO', (u'Angola')),
   ('AI', (u'Anguilla'))
)

print (country for (code, country) in COUNTRIES if code=='AD').next()
#>>> Andorra

print next((country for (code, country) in COUNTRIES if code=='AD'), None)
#Andorra
print next((country for (code, country) in COUNTRIES if code=='Blah'), None)
#None

# If you want to do multiple lookups, the best is to make a dict:
d = dict(COUNTRIES)
print d['AD']
#>>> Andorra
like image 44
robert king Avatar answered Sep 19 '22 20:09

robert king