Saturday, February 17, 2018


Dictionaries allows you to connect pieces of related information:
favoritesTeams = {'Real Madrid':'Spain','FC Barcelona':'Spain'}

print(favoritesTeams['Real Madrid'])
print(favoritesTeams['FC Barcelona'])

In a dictionary you have two values(key:value). In order to print the value for a key: 
print(favoritesTeams['Real Madrid'])


Adding New key-values pairs:
favoritesTeams['Arsenal'] = 'US'
favoritesTeams['Schalke 04'] = 'Germany'

We could also create a dictionary with no values:
newDic = {}

newDic['Madrid'] = 'Spain'
newDic['Miami'] = 'US'

Modifying values in a Dictionary:
newDic['Madrid'] = 'EspaƱa'

Delete key-value pairs:
del newDic['Madrid'] 

Looping through a Dictionary: 
newDic = {
'Real Madrid' : 'Spain',
'FC Barcelona':'Spain',
'Arsenal': 'England';

for key, value in newDic.items():
    print('Key: '  + key)
    print('Value: ' + value)

Key: Real Madrid
Value: Spain

Key: FC Barcelona
Value: Spain

Key: Arsenal
Value: England

We can also loop through all the keys:
for i in newDic.keys():

Real Madrid
FC Barcelona

We could also have written(same output): 
 for i in newDic():

Looping through a dictionary's keys in order:
for i in sorted(newDic.keys()):
          print(i + ", is one of my favorite teams")

Real Madrid is one of my favorite teams
FC Barcelona is one of my favorite teams
Arsenal is one of my favorite teams

To loop through the values is the same as looping through the keys but instead we use the word value: for i in newDic.values()

Creating a List of Dictionaries:
visitedCities = {'Miami':'Florida',
bucketList= {'Madrid':'Spain',

cities = [visitedCities, bucketList]

for i in cities:

Creating a List in a Dictionary: 
myTeam= { 'team': 'Real Madrid', 'Players': ['Ramos', 'Marcelo', 'Ronaldo'],}

print("My favorite team is: " + myTeam['team'] + " FC" + " and my favorite players are: ")
for i in myTeam['Players']:          

My favorite team is: Real Madrid FC and my favorite players are: 


Dictionary in a Dictionary:
favPlayersList= {
   'Ronaldo': {
   'first': 'Cristiano',
   'last': 'Ronaldo',
   'team': 'Real Madrid',
   'Messi': {
   'first': 'Lionel',
   'last': 'Messi',
   'team': 'FC Barcelona',

for i, j in favPlayersList.items():
   print("\tFavorite Soccer Players: " + i)
   full_name = j['first'] + " " + j['last']
   team= j['team']
   print("\tFull name: " + full_name.title())
   print("\tCurrent Team: " + team.title())

No comments:

Post a Comment