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?
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() .
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
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, *.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With