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

How is a dictionary implemented in Python?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-08-18 22:01:08
forward
828 people have browsed it

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"
}
Copy after login

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

Dictionary = {
   Key: "Value",
   Key : "Value", . . . . . Key : "Value"
}
Copy after login

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”
Copy after login

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”
Copy after login

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
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template