Python dictionary is another mutable container model and can store any type of object, such as strings, numbers, tuples and other container models.
1. Create a dictionary
A dictionary consists of pairs of keys and corresponding values. Dictionaries are also called associative arrays or hash tables. The basic syntax is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
You can also create a dictionary like this
dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 }
Note:
Each key and value are separated by a colon (:), each pair is separated by a comma, and each pair is separated by a comma. Split and place the whole in curly braces ({}).
Keys must be unique, but values do not.
The value can be of any data type, but it must be immutable, such as string, number or tuple.
Modify the dictionary:
The way to add new content to the dictionary is to add new key/value pairs, modify or delete existing key/value pairs as follows:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry print "dict['Age']: ", dict['Age']; print "dict['School']: ", dict['School']; #以上实例输出结果: #dict['Age']: 8 #dict['School']: DPS School
More Python For related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to enter values into dictionary in python. For more information, please follow other related articles on the PHP Chinese website!