Home > Backend Development > Python Tutorial > How to use dictionary in python? Use of python dictionary

How to use dictionary in python? Use of python dictionary

青灯夜游
Release: 2018-10-19 16:32:02
forward
3956 people have browsed it

The content of this article is to introduce how to use dictionary in python? How to use python dictionary. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Dictionaries, like sets, are unordered and cannot be accessed through indexes, but only through keys.

The keys of the dictionary must be immutable data types, such as numbers, strings, tuples, etc. Mutable objects such as lists cannot be used as keys.

Create dictionary and add and remove dictionary:

#创建字典
a = {'name':'xiaobin','age':18}
print(a)
b = dict(name = 'xiaobin',age = '18')
print(b)

#字典的添加,键不重名的添加,重名的会覆盖更新
a['from'] = 'anhui'
print(a)
a.update({'hobby':'football','age':20})
print(a)

#字典元素的去除
b = a.pop('age')
print(b)
print(a)

运行结果:
{'name': 'xiaobin', 'age': 18}
{'name': 'xiaobin', 'age': '18'}
{'name': 'xiaobin', 'age': 18, 'from': 'anhui'}
{'name': 'xiaobin', 'age': 20, 'from': 'anhui', 'hobby': 'football'}
18
{'name':'xiaobin'}
Copy after login

Modification of dictionary:

info  = {'a':[1,2,4],'b':[4,5,6]}
info['a'][2] = 3
print(info)
运行结果:{'a': [1, 2, 3], 'b': [4, 5, 6]}
Copy after login

Membership of dictionary:

#成员关系
a = {'a':1,'b':2}
print('b' in a)
运行结果:True
Copy after login

Method of dictionary:

a = {'a':1,'b':2}
print(a.keys())
print(a.values())
print(a.items())

运行结果:
dict_keys(['a', 'b'])
dict_values([1, 2])
dict_items([('a', 1), ('b', 2)])
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related video tutorials, please visit: Python video tutorial, Python3 video tutorial, bootstrap video tutorial!

The above is the detailed content of How to use dictionary in python? Use of python dictionary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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