Web
Analytics
Dictionary in Python | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

What is Dictionary

  • a built-in data structure available in Python
  • a dictionary is a sequence of key-value, or item, pairs separated by commas.
  • Ex

port = {22: “SSH”, 23: “Telnet” , 53: “DNS”, 80: “HTTP” }

  • . In a list, values are indexed by the range of numbers, but in a dictionary, values are indexed by keys.
  • Syntax

Dictionary_name = {key: value}

Key Features:

  • The key of the dictionary can not be changed
  • A string, int, or float can be used as a key
  • Keys are unique Values can be anything, for example, list, string, int, and so on
  • Values can be repeated Values can be changed
dic1 = {'fname':20,'lname':10,'age':50}
print(dic1)
print(dic1['fname'])
#del dic1['lname']
#print(dic1)
print(max(dic1))
# Min
print(min(dic1))
# Copy Method
dic2=dic1.copy()
print(dic2)
# Two dictionary object will be created at different memory locations
# Get Method
print(dic1.get('fname'))
# Output:20
print(dic1.get('fname1','not found'))
# Output Not found
# Set Value
dic1.setdefault('add','pratap nagar')
print(dic1)
# Output: {'fname': 20, 'lname': 10, 'age': 50, 'add': 'pratap nagar'}

# has key method
print(dic1.keys())
# Output : dict_keys(['fname', 'lname', 'age', 'add'])
# Values
print(dic1.values())
# Output : dict_values([20, 10, 50, 'pratap nagar'])

# Update
dic3 = {'hobbies':'dancing','award':'first'}
dic1.update(dic3)
print(dic1)
# Output : {'fname': 20, 'lname': 10, 'age': 50, 'add': 'pratap nagar', 'hobbies': 'dancing', 'award': 'first'}

#Items
print(dic1.items())
# Output : dict_items([('fname', 20), ('lname', 10), ('age', 50), ('add', 'pratap nagar'), ('hobbies', 'dancing'), ('award', 'first')])

# Clear Method
#print('clear method output is ')
#print(dic1.clear())
# Output:  clear method output is
#None

# For Loop
for k,v in dic1.items():
    print('key{0}:value{1}'.format(k,v))
# Output
"""keyfname:value20
keylname:value10
keyage:value50
keyadd:valuepratap nagar
keyhobbies:valuedancing
keyaward:valuefirst"""