A summary of common operation methods in Python dictionary dict _python

Source: Internet
Author: User

The example of this article summarizes the common operation methods of Dict dictionary in Python. Share to everyone for your reference. Specifically as follows:

The following Python code shows the common operation of the dictionary in Python, the dictionary plays a pivotal role in Python development, and mastering the dictionary operation is very important

#创建一空字典
x = {}
#创建包含三个项目的字典
x = {"One": 1, "two": 2, "three": 3}
#访问其中的一个元素
x[' two ']
# Returns the list of all the keys in the dictionary
X.keys ()
#返回字典中的所有值列表
x.values ()
#添加一个新的项目
x["Four"]=4
#修改一个字典项目
x ["one"] = "Uno"
#删除一个字典项目
del x["four"]
#复制一个字典到新的变量
y = x.copy ()
#清除所有字典项目
x.clear ()
#返回字典长度, number of items
z = Len (x)
#检测字典是否包含了指定的key
z = X.has_key ("one") #遍历字典中的key for
item in X.keys (): Print item
#遍历字典中的值列表 for
item in X.values (): Print item
#使用if语句获取字典中相应的键值
if ' one ' in x:< C30/>print x[' one ']
if "two" not in X:
  print "Two not found"
if "three" in X:
  del x[' three ']

I hope this article will help you with your Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.