Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Remove Key/Value Pairs from a Dictionary

Python Remove Key/Value Pairs from a Dictionary

Document Object Reference Manual Python3 Examples

Given a dictionary, remove key/value pairs from it.

Example 1: remove with del

test_dict

= {

"

Runoob

"

:

1

,

"

Google

"

:

2

,

"

Taobao

"

:

3

,

"

Zhihu

"

:

4

}

Print the original dictionary

print

(

"

Dictionary before removal:

"

str

(

test_dict

)

)

Use del to remove Zhihu

del

test_dict

[

'

Zhihu

'

]

Print the dictionary after removal

print

(

"

Dictionary after removal:

"

str

(

test_dict

)

)

Removing a key that does not exist raises an error

#del test_dict['Baidu']

The output of the code above is:


字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除后 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}

Example 2: remove with pop()

test_dict

= {

"

Runoob

"

:

1

,

"

Google

"

:

2

,

"

Taobao

"

:

3

,

"

Zhihu

"

:

4

}

Print the original dictionary

print

(

"

Dictionary before removal:

"

str

(

test_dict

)

)

Use pop to remove Zhihu

removed_value

=

test_dict

.

pop

(

'

Zhihu

'

)

Print the dictionary after removal

print

(

"

Dictionary after removal:

"

str

(

test_dict

)

)

print

(

"

The value corresponding to the removed key is:

"

str

(

removed_value

)

)

print

(

'

\r

'

)

Using pop() to remove a key that does not exist does not raise an exception; we can customize the message

removed_value

=

test_dict

.

pop

(

'

Baidu

'

,

'

No such key

'

)

Print the dictionary after removal

print

(

"

Dictionary after removal:

"

str

(

test_dict

)

)

print

(

"

The removed value is:

"

str

(

removed_value

)

)

The output of the code above is:


字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除后 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
移除的 key 对应的 value 为 : 4

字典移除后 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}
移除的值为 : 没有该键(key)

Example 3: remove with items()

test_dict

= {

"

Runoob

"

:

1

,

"

Google

"

:

2

,

"

Taobao

"

:

3

,

"

Zhihu

"

:

4

}

Print the original dictionary

print

(

"

Dictionary before removal:

"

str

(

test_dict

)

)

Use pop to remove Zhihu

new_dict

= {

key

:

val

for

key

,

val

in

test_dict

.

items

(

)

if

key

!=

'

Zhihu

'

}

Print the dictionary after removal

print

(

"

Dictionary after removal:

"

str

(

new_dict

)

)

The output of the code above is:


字典移除前 : {'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
字典移除后 : {'Runoob': 1, 'Google': 2, 'Taobao': 3}

Document Object Reference Manual Python3 Examples