Dictionaries - Python

  • varD = {key1: "value1", key2: "value2"} => Initialize a dictionary
    • Ordered collection
    • varD = {} => Initialize an empty dictionary
  • varD[key] = "value" => Update or Add a new value
    • varD.update(varD1) => Appends varD1 into the dictionary
  • del varD => Deletes entire dictionary
    • del varD[key] => Deletes key-value pair
    • varD.clear() => Clears all the elements from the dictionary
    • varName = varD.pop(key) => Removes and Return the given key-value pair
    • varName = varD.popItem() => Removes and Return the last key-value pair
  • varD[key] => Returns values of that key if present else returns error
    • varD.get(key) => Returns values of that key if present else returns "none"
    • varD.keys() => Returns all the keys
    • varD.values() => Returns all the values
    • varT = varD.items() => Returns all the pairs as a sequence of (key,value) tuples in random order
    • Loop in the dictionary
          for key in varD.keys():
              print(key) # Prints all the keys
              print(varD[key]) # Prints all the values
          for key, value in varD.items():
              print(key) # Prints all the keys
              print(value) # Prints all the values
      
  • len(varD) => Gives the count of pairs
  • varD2 = varD1.copy() => Creates a copy of varD1 into variable varD2
Share: