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
      Access 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.

      Access Dictionary Items

      Using the "[ ]" Operator

      A dictionary in Python is not a sequence, as the elements in dictionary are not indexed. Still, you can use the square brackets "[ ]" operator to fetch the value associated with a certain key in the dictionary object.

      Example 1

      capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
      print ("Capital of Gujarat is : ", capitals['Gujarat'])
      print ("Capital of Karnataka is : ", capitals['Karnataka'])
      It will produce the following output
      Capital of Gujarat is: Gandhinagar
      Capital of Karnataka is: Bengaluru

      Example 2

      Python raises a KeyError if the key given inside the square brackets is not present in the dictionary object.
      capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
      print ("Captial of Haryana is : ", capitals['Haryana'])
      It will produce the following output
      print ("Captial of Haryana is : ", capitals['Haryana'])
      ~~~~~~~~^^^^^^^^^^^
      KeyError: 'Haryana'

      Using the get() Method

      The get() method in Python's dict class returns the value mapped to the given key.

      Syntax

      Val = dict.get("key")

      Parameters

      • key − An immutable object used as key in the dictionary object

      Return Value

      The get() method returns the object mapped with the given key.

      Example 3

      capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
      print ("Capital of Gujarat is: ", capitals.get('Gujarat'))
      print ("Capital of Karnataka is: ", capitals.get('Karnataka'))
      It will produce the following output
      Capital of Gujarat is: Gandhinagar
      Capital of Karnataka is: Bengaluru

      Example 4

      Unlike the "[]" operator, the get() method doesn't raise error if the key is not found; it return None.
      capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
      print ("Capital of Haryana is : ", capitals.get('Haryana'))
      It will produce the following output
      Capital of Haryana is : None

      Example 5

      The get() method accepts an optional string argument. If it is given, and if the key is not found, this string becomes the return value.
      capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
      print ("Capital of Haryana is : ", capitals.get('Haryana', 'Not found'))
      It will produce the following output
      Capital of Haryana is: Not found

      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.