Teachnique
      CourseRoadmaps
      Login

      OverviewCommentsUser InputNumbersBooleansHistoryHello World ProgramEnvironment SetupSyntaxVariablesData TypesType CastingUnicode SystemLiteralsOperators

      Control FlowBreak StatementContinue StatementPass StatementNested LoopsDecision MakingIf StatementIf-else StatementNested IF StatementMatch-Case StatementLoopsFor LoopsFor-else LoopsWhile Loops

      FunctionsBuilt-in FunctionsDefault ArgumentsKeyword ArgumentsKeyword-Only ArgumentsPositional ArgumentsPositional-Only ArgumentsArbitrary ArgumentsVariable ScopeFunction AnnotationsModules

      StringSlicing StringsModify StringsString ConcatenationString FormattingEscape CharactersString MethodsString Exercises

      ListsList ExercisesAccess List ItemsChange List ItemsAdd List ItemsRemove List ItemsLoop ListsList ComprehensionSort ListsCopy ListsJoin ListsList Methods

      TuplesAccess Tuple ItemsUpdate TuplesUnpack Tuple ItemsLoop TuplesJoin TuplesTuple MethodsTuple Exercises

      SetsAccess Set ItemsAdd Set ItemsRemove Set ItemsLoop SetsJoin SetsCopy SetsSet OperatorsSet MethodsSet Exercises

      DictionariesDictionary ExercisesAccess Dictionary ItemsChange Dictionary ItemsAdd Dictionary ItemsRemove Dictionary ItemsDictionary View ObjectsLoop DictionariesCopy DictionariesNested DictionariesDictionary Methods

      ArraysAccess Array ItemsAdd Array ItemsRemove Array ItemsLoop ArraysCopy ArraysReverse ArraysSort ArraysJoin ArraysArray MethodsArray Exercises

      File HandlingWrite to FileRead FilesRenaming and Deleting FilesDirectoriesFile Methods

      OOP ConceptsDynamic BindingDynamic TypingAbstractionObject and ClassesEncapsulationInterfacesPackagesInner ClassesAnonymous Class and ObjectsSingleton ClassWrapper ClassesEnumsReflectionClass AttributesClass MethodsStatic MethodsConstructorsAccess ModifiersInheritancePolymorphismMethod OverridingMethod Overloading

      Feedback

      Submit request if you have any questions.

      Course
      Add Dictionary Items

      Python Tutorial

      This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.

      Add Dictionary Items

      Using the Operator

      The "[]" operator (used to access value mapped to a dictionary key) is used to update an existing key-value pair as well as add a new pair.

      Syntax

      dict["key"] = val
      If the key is already present in the dictionary object, its value will be updated to val. If the key is not present in the dictionary, a new key-value pair will be added.

      Example

      In this example, the marks of "Laxman" are updated to 95.
      marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
      print ("marks dictionary before update: ", marks)
      marks['Laxman'] = 95
      print ("marks dictionary after update: ", marks)
      It will produce the following output
      marks dictionary before update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
      marks dictionary after update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 95, 'David': 49}

      Example

      However, an item with 'Krishnan' as its key is not available in the dictionary, hence a new key-value pair is added.
      marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
      print ("marks dictionary before update: ", marks)
      marks['Krishan'] = 74
      print ("marks dictionary after update: ", marks)
      It will produce the following output
      marks dictionary before update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
      marks dictionary after update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49, 'Krishan': 74}

      Using the update() Method

      You can use the update() method in dict class in three different ways:

      Update with Another Dictionary

      In this case, the update() method's argument is another dictionary. Value of keys common in both dictionaries is updated. For new keys, key-value pair is added in the existing dictionary

      Syntax

      d1.update(d2)

      Return value

      The existing dictionary is updated with new key-value pairs added to it.

      Example

      marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
      print ("marks dictionary before update: \n", marks)
      marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89}
      marks.update(marks1)
      print ("marks dictionary after update: \n", marks)
      It will produce the following output
      marks dictionary before update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
      marks dictionary after update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

      Update with Iterable

      If the argument to update() method is a list or tuple of two item tuples, an item each for it is added in the existing dictionary, or updated if the key is existing.

      Syntax

      d1.update([(k1, v1), (k2, v2)])

      Return value

      Existing dictionary is updated with new keys added.

      Example

      marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
      print ("marks dictionary before update: \n", marks)
      marks1 = [("Sharad", 51), ("Mushtaq", 61), ("Laxman", 89)]
      marks.update(marks1)
      print ("marks dictionary after update: \n", marks)
      It will produce the following output
      marks dictionary before update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
      marks dictionary after update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.
      

      Update with Keyword Arguments

      Third version of update() method accepts list of keyword arguments in name=value format. New k-v pairs are added, or value of existing key is updated.

      Syntax

      d1.update(k1=v1, k2=v2)

      Return value

      Existing dictionary is updated with new key-value pairs added.

      Example

      marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
      print ("marks dictionary before update: \n", marks)
      marks.update(Sharad = 51, Mushtaq = 61, Laxman = 89)
      print ("marks dictionary after update: \n", marks)
      It will produce the following output
      marks dictionary before update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
      marks dictionary after update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

      Using the Unpack Operator

      The "**" symbol prefixed to a dictionary object unpacks it to a list of tuples, each tuple with key and value. Two dict objects are unpacked and merged together and obtain a new dictionary.

      Syntax

      d3 = {**d1, **d2}

      Return value

      Two dictionaries are merged and a new object is returned.

      Example

      marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
      print ("marks dictionary before update: \n", marks)
      marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89}
      newmarks = {**marks, **marks1}
      print ("marks dictionary after update: \n", newmarks)
      It will produce the following output
      marks dictionary before update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
      marks dictionary after update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

      Using the Union Operator (|)

      Python introduces the "|" (pipe symbol) as the union operator for dictionary operands. It updates existing keys in dict object on left, and adds new key-value pairs to return a new dict object.

      Syntax

      d3 = d1 | d2

      Return value

      The Union operator return a new dict object after merging the two dict operands

      Example

      marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
      print ("marks dictionary before update: \n", marks)
      marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89}
      newmarks = marks | marks1
      print ("marks dictionary after update: \n", newmarks)
      It will produce the following output
      marks dictionary before update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
      marks dictionary after update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

      Using "|=" Operator

      The "|=" operator is an augmented Union operator. It performs in-place update o n the dictionary operand on left by adding new keys in the operand on right, and updating the existing keys.

      Syntax

      d1 |= d2

      Example

      marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49}
      print ("marks dictionary before update: \n", marks)
      marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89}
      marks |= marks1
      print ("marks dictionary after update: \n", marks)
      It will produce the following output
      marks dictionary before update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
      marks dictionary after update:
      {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.