Python Dictionary 3

How to access elements from a dictionary?

While indexing is used with other container types to access values, the dictionary uses keys. Key can be used either inside square brackets or with the get() method.

The difference while using get() is that it returns None instead of KeyError if the key is not found.

#to maintain roll and name
n={1:”amit”,2:”sumit”,3:”kapil”,4:”harsh”}
print(n)

Output:
{1: ‘amit’, 2: ‘sumit’, 3: ‘kapil’, 4: ‘harsh’}

#to maintain roll and name
n={1:"amit",2:"sumit",3:"kapil",4:"harsh"}
print(n)
#Output
{1: 'amit', 2: 'sumit', 3: 'kapil', 4: 'harsh'}
>>> 

#to maintain name and balance

n2={“rohit”:2000,”ajay”:5000,”kapil”:9000}
print(n2)

Output:
{‘rohit’: 2000, ‘ajay’: 5000, ‘kapil’: 9000}

#to maintain name and balance
n2={"rohit":2000,"ajay":5000,"kapil":9000}
print(n2)
#Output
{'rohit': 2000, 'ajay': 5000, 'kapil': 9000}
>>> 

To fetch the elements using keys
#to maintain roll and name

n={1:”amit”,2:”sumit”,3:”kapil”,4:”harsh”}
print(n)
print(n[1])
print(n[2])
print(n[3])

Output:

{1: ‘amit’, 2: ‘sumit’, 3: ‘kapil’, 4: ‘harsh’}
amit
sumit
kapil

#to maintain roll and name
n={1:"amit",2:"sumit",3:"kapil",4:"harsh"}
print(n)
print(n[1])
print(n[2])
print(n[3])
#Output
{1: 'amit', 2: 'sumit', 3: 'kapil', 4: 'harsh'}
amit
sumit
kapil
>>> 

# to maintain roll, name, age and per and fetch the details

n={“roll”:101,”name”:”Ajay”,”age”:21,”per”:99}
print(n)
print(n.get(“roll”))
print(n.get(“name”))
print(n.get(“age”))
print(n.get(“per”))

Output:

{‘roll’: 101, ‘name’: ‘Ajay’, ‘age’: 21, ‘per’: 99}
101
Ajay
21
99

# to maintain roll, name, age and per and fetch the details
n={"roll":101,"name":"Ajay","age":21,"per":99}
print(n)
print(n.get("roll"))
print(n.get("name"))
print(n.get("age"))
print(n.get("per"))
#Output
{'roll': 101, 'name': 'Ajay', 'age': 21, 'per': 99}
101
Ajay
21
99
>>> 

Note: if key is not present then “None” is returned
print(n.get(“address”))
None
Note: “address” key is not present so “None” is returned

 

# to maintain roll, name, age and per and fetch the details
n={"roll":101,"name":"Ajay","age":21,"per":99}
print(n)
print(n.get("roll"))
print(n.get("name"))
print(n.get("age"))
print(n.get("per"))
#Key address is not present
print(n.get("address"))
#Output
{'roll': 101, 'name': 'Ajay', 'age': 21, 'per': 99}
101
Ajay
21
99
None
>>> 

Visitor Counter

0051139