Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python Dictionary


May 10, 2021 Python2


Table of contents


Python Dictionary

A dictionary is another variable container model and can store any type of object.

Each key value of the dictionary is split with a colon (:), and between each pair is split with a comma (,), and the entire dictionary is included in the parenthesis (') in the following format:

d = {key1 : value1, key2 : value2 }

The key must be unique, but the value does not have to be.

Values can take any data type, but keys must be immeascondable, such as strings, numbers, or yuans.

A simple dictionary example:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can also create a dictionary like this:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

Access the values in the dictionary

Put the appropriate keys into familiar square brackets, as follows:

#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];

The above example output results:

dict['Name']:  Zara
dict['Age']:  7

If you access data with keys that are not in the dictionary, the output error is as follows:

#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
print "dict['Alice']: ", dict['Alice'];

The above example output results:

dict['Zara']:
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Modify the dictionary

The way to add new content to the dictionary is to add a new key/value pair and modify or delete an existing key/value pair as follows:

#!/usr/bin/python
 
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'];

The above example output results:

dict['Age']:  8
dict['School']:  DPS School

Delete the dictionary element

Can delete a single element can also empty the dictionary, emptying only one operation.

The display removes a dictionary with the del command, as follows:

#coding=utf-8
#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
del dict['Name']; # 删除键是'Name'的条目
dict.clear();     # 清空词典所有条目
del dict ;        # 删除词典
 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

However, this throws an exception because the dictionary no longer exists after del:

dict['Age']:
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

Note: The del() method is also discussed later.


The characteristics of the dictionary key

Dictionary values can take any Python object without restriction, neither a standard object nor a user-defined object, but the key does not.

There are two important points to keep in mind:

1) The same key is not allowed to appear twice. If the same key is assigned twice when it is created, the last value is remembered, as in the following example:

#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
 
print "dict['Name']: ", dict['Name'];

The above example output results:

dict['Name']:  Manni

2) The key must be imm changed, so you can use numbers, strings, or metagroups, so you can't use lists, as in the following examples:

#!/usr/bin/python
 
dict = {['Name']: 'Zara', 'Age': 7};
 
print "dict['Name']: ", dict['Name'];

The above example output results:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable


Dictionary built-in functions and methods

The Python dictionary contains the following built-in functions:

Serial number Functions and descriptions
1 cmp(dict1, dict2)
Compare two dictionary elements.
2 len(dict)
Calculates the number of dictionary elements, which is the total number of keys.
3 str(dict)
The output dictionary can print a string represented.
4 type(variable)
Returns the type of variable entered, and returns the dictionary type if the variable is a dictionary.

The Python dictionary contains the following built-in functions:

Serial number Functions and descriptions
1 radiansdict.clear()
Delete all elements in the dictionary
2 radiansdict.copy()
Returns a shallow copy of a dictionary
3 radiansdict.fromkeys()
Create a new dictionary with the elements in the sequence seq as the keys to the dictionary, and val is the initial value for all keys in the dictionary
4 radiansdict.get(key, default=None)
Returns the value of the specified key, if the value does not return the default value in the dictionary
5 radiansdict.has_key(key)
If the key returns True in the dictionary dict, otherwise false is returned
6 radiansdict.items()
Returns an array of traversable (key, value) yuans in a list
7 radiansdict.keys()
Returns all the keys of a dictionary in a list
8 radiansdict.setdefault(key, default=None)
Similar to get(), but if the key does not already exist in the dictionary, the key is added and the value is set to default
9 radiansdict.update(dict2)
Update the key/value pair of the dictionary dict2 to the dict
10 radiansdict.values()
Returns all values in the dictionary in a list

Instance:

Use Python to write a dictionary program:

  1. The user adds words and definitions
  2. Look for these words
  3. If you can't find it, let the user know
  4. Cycle

The code is as follows:

#coding:utf-8

# 字典创建  while开关 字典添加   字典寻找
dictionary = {}
flag = 'a'
pape = 'a'
off = 'a'
while flag == 'a' or 'c' :
    flag = raw_input("添加或查找单词 ?(a/c)")
    if flag == "a" :                             # 开启
        word = raw_input("输入单词(key):")
        defintion = raw_input("输入定义值(value):")
        dictionary[str(word)] = str(defintion)  # 添加字典
        print "添加成功!"
        pape = raw_input("您是否要查找字典?(a/0)")   #read
        if pape == 'a':
            print dictionary
        else :
            continue
    elif flag == 'c':
        check_word = raw_input("要查找的单词:")  # 检索
        for key in sorted(dictionary.keys()):            # yes
            if str(check_word) == key:
                print "该单词存在! " ,key, dictionary[key]
                break
            else:                                       # no
                off = 'b'
        if off == 'b':
            print "抱歉,该值不存在!"
    else:                               # 停止
        print "error type"
        break

The test results are as follows:

添加或查找单词 ?(a/c)a

输入单词(key):w3c

输入定义值(value):w3cschool.cn

添加成功!

您是否要查找字典?(a/0)0

添加或查找单词 ?(a/c)c

要查找的单词:w3c

该单词存在!  w3c w3cschool.cn

添加或查找单词 ?(a/c)