Friday, 4 November 2016

Python comprehensions

Python comprehensions


Python list comprehension to convert all characters to upper case.

>>> countries = ['america', 'india', 'england']
>>>
>>> countries_to_upper = map(str.upper, [country for country in countries ])
>>> print countries_to_upper

['AMERICA', 'INDIA', 'ENGLAND']

Python set comprehension to convert all characters to upper case.

>>> countries = ['america', 'india', 'england', 'america']
>>> countries_to_upper = map(str.upper, {country for country in countries })
>>> print countries_to_upper

['ENGLAND', 'AMERICA', 'INDIA']

Python dict comprehension

>>> countries = [{ 'name': 'america'}, {'name':'india'}, {'name':'england'}]
>>> countries_with_new_key = [{'country_name':country['name']}  for country in countries ]
>>> countries_with_new_key
[{'country_name': 'america'}, {'country_name': 'india'}, {'country_name': 'england'}]

No comments:

Post a Comment