Week 3 - Understanding Dictionaries & List comprehension

Liaw Bei Le · April 5, 2021

  1. Dictionaries in Python and how to use them.
  2. List comprehension

What I learnt:

1. Dictionaries

  • Key value pairs
    • Key:Value is a Key-value pair
  • Dictionary
    • {Key:Value} is a Dictionary
      d={'word':'meaning', 'word2':'meaning2'}
      d2={1:2, 'l1':[1, 2, 3], 'd3':{'a':'b', 'c':'d'}}
      
    • dictionary[key] gives the key’s value as output
    • dictionary.get(key, ‘key not found’)
      gives the key as output if it is in the list, and if not, gives ‘key not found’ as output instead
    • dictionary.keys() gives all keys in a list
    • dictionary.values() gives all values in a list
    • dictionary.items() gives all key value pairs in tuples in a list
      capitals={'India':'Delhi', 'Malaysia':'LK', 'France':'Paris', 'Singapore':'Singapore'}  
      print(capitals['India'])
      print(capitals.get('Singapore', 'Country Not Present'))
      print(capitals.keys())
      print(capitals.values())
      print(capitals.items())
      

      Output

         Delhi
         Delhi
         dict_keys(['India', 'Malaysia', 'France', 'Singapore'])
         dict_values(['Delhi', 'LK', 'Paris', 'Singapore'])
         dict_items([('India', 'Delhi'), ('Malaysia', 'LK'), ('France', 'Paris'), ('Singapore', 'Singapore')])
      
    • Iterate through a dictionary
      for variablekey, variablevalue in dictionary.items( ):
      print(f”Value of {variablekey} is {variablevalue}”)
      for country, capital in capitals.items():
        print(f"Capital of {country} is {capital}")
      

      Output

        Capital of India is Delhi
        Capital of Malaysia is LK
        Capital of France is Paris
        Capital of Singapore is Singapore
      
    • Update a dictionary (Add key-value pair / change value)
      dictionary[key]=value
        capitals['China']='Beijing'
      capitals['Malaysia']='KL'
      print(capitals)
      

      Output

        {'India': 'Delhi', 'Malaysia': 'KL', 'France': 'Paris', 'Singapore': 'Singapore', 'China': 'Beijing'}
      
    • Print length of dictionary
      • print(len(dictionary))
    • Remove Key-Value pair from dictionary
      • del dictionary[Key]

Practices

  • Check input equals value
    check_input={'Sum':'sum', 'SUm':'sum', 'sum':'sum', 'Power':'power',\
               'power':'power'}
    user_input=input('What Do you want to do?')
    num1=5
    num2=10
    if check_input[user_input]=='sum':
      print(num1+num2)
    elif check_input[user_input]=='power':
      print(num1**num2)
    else:
      print('Wrong input')
    
  • From a dictionary, create a list of the values only
    capitals={'India':'Delhi', 'Malaysia':'LK', 'France':'Paris', 'Singapore':'Singapore'}
    keylist = capitals.keys()
    new_list = []
    for key in keylist:
      new_list.append(capitals[key])
    print(new_list)
    

    or

    capitals={'India':'Delhi', 'Malaysia':'LK', 'France':'Paris', 'Singapore':'Singapore'}
    valuelist = capitals.values()
    print(valuelist)
    

2. List Comprehension

  • **[item for item in list if ==True]**
    • means to append item into an empty list, for item in list, if condition met
  • Using character in a string / list
  • Using ‘‘.join(list) to join elements in a list

Practices

  • Create a list with only even numbers of the given list
    list1=[5, 8, 11, 15, 19]
    [number for number in list1 if number%2==0]
    
  • Create a list of number+1 (i.e. n+1) for only even numbers (n) of the given list
    list1=[5, 8, 11, 15, 19]
    [number+1 for number in list1 if number%2==0]
    
  • Create a list of capitals from the given dictionary
    countries=['India', 'Singapore', 'Japan', 'France', 'Malaysia']
    capitals={'India':'Delhi', 'Malaysia':'LK', 'France':'Paris', 'Singapore':'Singapore'}
    [capitals[country] for country in countries]
    
  • Create a list of the lengths of the capitals from the given dictionary
    countries=['India', 'Singapore', 'Japan', 'France', 'Malaysia']
    capitals={'India':'Delhi', 'Malaysia':'LK', 'France':'Paris', 'Singapore':'Singapore'}
    [len(capitals[country]) for country in countries]
    
  • Use list comprehension, return a list of lengths of each word in the sentence except ‘the’
    sentence="the quick brown fox jumped over the lazy bear"
    text_list=sentence.split(" ")
    [text for text in text_list if text!="the"]
    
  • Use list comprehension on the sentence to remove all vowels and print the sentence (not as a list but as a string)
    #use 'not in' and ' '.join(list)
    sentence="the quick brown fox jumped over the lazy bear"
    vowels=['a','e','i','o','u']
    sentencelist = [character for character in sentence if character not in vowels]
    joinedstrings=''.join(sentencelist)
    print(joinedstrings)
    
  • Print all the unique items & characters in a list
    sentence="the quick brown fox jumped over the lazy bear"
    #Print all unique items
    #use 'not in' and string.split(' ')
    list_sentence=sentence.split(' ')
    newlist=[]
    for word in list_sentence:
      if word not in newlist:
          newlist.append(word)
    print(newlist)
    #Print all unique characters
    sentence_list=[character for character in sentence]
    new_list=[]
    for text in sentence_list:
      if text not in new_list:
          newlist.append(text)
    print(new_list)
    

More Other Practices

  • Find length of a list w/o len( ) function
    list1=[5, 8, 11, 15, 19]
    count=0
    for number in list1:
      count = count+1
    print(count)
    

    Then, create a list with only even numbers of the first list

    list2=[]
    for number in list1:
      if number%2==0:
          list2.append(number)
    print(list2)
    

    Find the number of items smaller than 12 for number in list1

    count=0
    for number in list1:
      if number<12:
          count = count+1
    print(count)
    
  • Find countries whose name is less than 6 letters. Put them in a list.
    countries=['India', 'Singapore', 'Japan', 'France', 'Malaysia']
    list3=[]
    for country in countries:
      if len(country)<6:
          list3.append(country)
    print(list3)
    
    if 'India' in countries:
      print('Yes')
    

    Find countries which is in the countries list above and also in the different_countries list below.

    different_countries=['USA', 'Mexico', 'Canada', 'Japan']
    if country in different_countries:
      print(country)
    

Thoughts

I’m quite proud of myself of having attempted quite a number of practices and getting myself familiar with Python.

List comprehension seems really efficient when appending items to a list while setting conditions as it could be done with just one line of code! I find this quite amazing.

I am thankful that my mentor taught me how to apply the codes in an efficient manner to get the desired output, as I probably would not have learnt how to this quickly on my own.

Twitter, Facebook