Home  >  Article  >  Backend Development  >  How is a dictionary implemented in Python?

How is a dictionary implemented in Python?

WBOY
WBOYforward
2023-08-18 22:01:08738browse

How is a dictionary implemented in Python?

In Python, dictionaries are like maps in C and Java. Like a Map dictionary, it consists of two parts: keys and values. Dictionaries are dynamic, you can add more keys and values ​​after creating the dictionary, and you can also delete keys and values ​​from the dictionary. You can add another dictionary to the currently created dictionary. You can also add lists to dictionaries and dictionaries to lists.

In a dictionary, you can access elements by their respective keys.

Dictionary = {
   1: "Apple", 2: "Ball", 3: "Caterpillar", 4: "Doctor",
   5: "Elephant"
}

Here, dictionary 1, 2, 3... represent keys, and "Apple", "Ball", "Caterpillar"... represent values.

Dictionary = {
   Key: "Value",
   Key : "Value", . . . . . Key : "Value"
}

Access elements

print(dictionary[1])
#print element whose key value is 1 i.e. “Apple”

print(dictionary[4])
# print element whose key value is 4 “Doctor”

Insert and update elements in the dictionary

Dictionary[6] = "Flesh"
# inserting element with key value 6 at last in dictionary

Dictionary[3] = "Cat"
# element with key value 3 is update with value “Cat”

Delete elements in the dictionary

Dictionary.pop(3)
# Delete element with key value 3

del Dictionary[4]
# delete element with key value 4

Dictionary.popitem()
# delete last inserted element in dictionary

del Dictionary
# this will delete whole dictionary

Built-in functions of dictionary in Python

  • Dictionary_2 = Dictionary.copy()

    This copy function will copy all values ​​of the dictionary to Dictionary_2

  • Dictionary.clear()

    clear() function will clear the entire dictionary.

  • Dictionary.get(2)

    The get() function will return the value of key 2.

  • Dictionary.values()

    This function will return all values ​​of the dictionary.

  • Dictionary.update({5:”Ears”})

    This function will update the value of the given key

The above is the detailed content of How is a dictionary implemented in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete