Python | Loop through Dictionary

Python | Loop through Dictionary

For Loop

You can use for loop , the Return value is Keys of Dictionary

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }
  
    for x in dictionary:

    print(x)

Output

    Fname
    Sname
    Year

You can use keys() Method for return a keys of dictionary

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }
  
    for x in dictionary.keys():

    print(x)

Output

    Fname
    Sname
    Year


now , You can return Values of dictionary

Example

   dictionary = {
          "Fname": "neel",
          "Sname": "patel",
          "Year":  1999 
        }
  
    x = dictionary.values()
    print(x)

Output

    dict_values(['neel', 'patel', 1999])


You can use values() Method for return a values of dictionary

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }
  
    for x in dictionary.values():
    print(x)

Output

    neel
    patel
    1999

Now, you get both things key and value but using items() method

Example

    dictionary = {
      "Fname": "neel",
      "Sname": "patel",
      "Year":  1999 
    }

  for x,y in dictionary.items():
        
    print(x,y)


Output
    
    Fname neel
    Sname patel
    Year 1999

Post a Comment (0)
Previous Post Next Post