Dictionary

  • A dictionary consists of a collection of key-value pairs.
  • Dictionary items are unordered, changeable, and does not allow duplicates.
  • Dictionaries cannot have two items with the same key.

Create

  • To create a dictionary declare key-value pairs enclosing a comma-separated in curly braces ({})
  • A colon (:) separates each key from its associated value.
# Creating a Dictionary

mydict= {1: 'Reviving', 'a': 'India', 34.5: 'Revin'}

print(mydict)

# Creating an empty Dictionary

mydict = {}

print("Empty Dictionary: ")

print(mydict)

Access Dictionary Items

  • The items of a dictionary can be accessed by referring to its key name, inside square brackets.
  • mydict[1]
  • get() method is also used to get the value of existing key in dictionary
  • x = mydict.get(1)
  • If we use the square brackets [], KeyErroris raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

Access all the keys

  • The keys() method will return a list of all the keys in the dictionary.
  • mydict.keys()

Access all the Values

  • The values()method will return a list of all the values in the dictionary.
  • mydict.values()

Key,value both Access

  • The items() method will return each item in a dictionary, as tuples in a list.
  • mydict.items()

Update Dict Items

  • The value of a specific item or key can be changed by referring to its key name.
  • mydict[1] = ’2021’
  • If the key will not exist in the dictionary , then it will add the key value pair rather than update.

Update method

The update() method will update the dictionary with the items from the given argument.

mydict.update({1: 58})

Remove Dict Items

  • pop – method removes the item with the specified key name
  • popitem(): method removes the last inserted item.
  • Del – keyword removes the item with the specified key name

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *