Friday, December 21, 2018

Python Dictionaries!

Create Python dictionaries, and access elements
cities = { 'United States': 'San Jose', 'France': 'Paris', 'Italy': 'Rome' }
cities['Italy']
Modify and merge data in dictionaries
# merge two dictionaries
more = {'Germany': 'Berlin', 'United Kingdom': 'London'}
cities.update( more )
Add and remove items in dictionaries
# adding
cities['Spain'] = 'Madrid'

try:
  cities['Germany']
except:
  print ('No Germinay city specified')

'Germany' in cities
# False
'Italy' in cities
# True

# delete items
del cities['United States']
Looping over the dictionaries
# loop over dict
for key in cities:
  print (key, cities[key])

for key in cities.keys():
  print (key, cities[key])

for value in cities.values():
  print (value)

for key,value in cities.items():
  print (key, value)

No comments:

Post a Comment