Python词典:如何使用它编写更好的代码

python词典是一种数据结构,类似于在其他编程语言中发现的关联数组。数组或列表按位置索引元素。另一方面,字典通过为元素建立索引,这些元素可以是字符串。将字典视为键-值对的无序集合。

在本文中,我们向您介绍使用python字典的工作。

创建字典

有多种创建python字典的方法。最简单的方法是使用括号初始化,其语法让人联想到JSON。

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}

您也可以将数字用作键。但是,请小心使用浮点数作为键,因为计算机会将它们存储为近似值。

rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}print rain_percentprint rain_percent[1980]# prints{1980: '17%', 1981: '15%', 1982: '10%'}17%

您还可以使用名称值对作为 dict()的关键字参数来创建和初始化字典。 构造函数。

population = dict(California=37253956, Colorado=5029196, Connecticut=3574097, Delaware=897934)print population# prints{'Connecticut': 3574097, 'Delaware': 897934, 'California': 37253956, 'Colorado': 5029196}

创建字典的另一种方法是使用键值元组数组。这是与上面相同的示例。

pairs = [('California', 37253956), ('Colorado', 5029196), ('Connecticut', 3574097), ('Delaware', 897934)]population = dict(pairs)print population# prints{'Connecticut': 3574097, 'Delaware': 897934, 'California': 37253956, 'Colorado': 5029196}

Dict理解提供了一种很酷的语法来初始化dict,前提是您可以基于键来计算值。以下代码初始化了一系列数字的数字和平方值的字典。

print {x: x**2 for x in xrange(10, 20)}# prints{10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361}

它如何工作?后面的部分(用于xrange(10,20)中的x的)返回指定范围内的数字范围。 dict理解部分( {x:x ** 2 ..} )在此范围内循环并初始化字典。

使用Python字典

创建字典后,该如何处理?好了,您可以访问元素,更新值,删除元素等。

使用方括号内的键访问字典的元素,就像数组或列表一样。

print population['Delaware']# prints897934

如果键是数字,则不需要引号。然后,该表达式看起来像是列表或数组索引。

print rain_percent[1980]# prints17%

访问键时,键的类型必须与Python字典中存储的键匹配。由于存储的键是数字,而访问键是字符串,所以以下内容会导致错误。

x = '1980'print rain_percent[x]# results in      1 x = '1980'----> 2 print rain_percent[x]KeyError: '1980'

访问不存在的键是错误。

rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}print rain_percent[1983]# prints      1 rain_percent = { 1980: '17%', 1981: '15%', 1982: '10%'}----> 2 print rain_percent[1983]KeyError: 1983

要访问键并在不存在映射的情况下提供默认值,请使用具有默认值的 get()方法作为第二个参数。

print rain_percent.get(1985, '0%')# prints0%

是否想在不实际尝试访问密钥的情况下检查密钥的存在(并可能遇到上述的 KeyError )?您可以使用 in 关键字,格式为dct中的,该布尔值返回一个布尔值。

print 1980 in rain_percentprint '1980' in rain_percent# printsTrueFalse

反转条件(即,确保键不是出现在Python字典中),其格式为 key in not dct 。这等效于标准python否定法不是dct中的键

print 1980 not in rain_percentprint 1985 not in rain_percent# printsFalseTrue

通过分配给所需的键来更改值。

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}users['age'] = 29print users# prints{'lastname': 'Smith', 'age': 29, 'firstname': 'John'}

使用相同的语法将新的映射添加到Python字典中。

users['dob'] = '15-sep-1971'print users# prints{'dob': '15-sep-1971', 'lastname': 'Smith', 'age': 29, 'firstname': 'John'}

使用 update()方法一次性更新字典中的多个元素。

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}users.update({'age': 29, 'dob': '15-sep-1971'})print users# prints{'dob': '15-sep-1971', 'lastname': 'Smith', 'age': 29, 'firstname': 'John'}

Set使用 setdefault()的键的默认值。如果映射不存在,则此方法设置键的值。它会返回当前值。

# does not change current valueprint users.setdefault('firstname', 'Jane')# printsJohn# sets valueprint users.setdefault('city', 'NY')# printsNY# Final valueprint users# prints{'lastname': 'Smith', 'age': 27, 'firstname': 'John', 'city': 'NY'}

使用 del 运算符删除字典中的映射。该运算符不返回任何内容。

如果字典中不存在该键,则将遇到 KeyError

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}del users['age']print users# prints{'lastname': 'Smith', 'firstname': 'John'}

使用弹出()方法,当您想要恢复已删除的值时。

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}print users.pop('age')print users# prints27{'lastname': 'Smith', 'firstname': 'John'}

如果您要删除某个键(如果存在)而又不会导致错误,该怎么办?您可以使用 pop()并为第二个参数指定 None ,如下所示:

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}users.pop('foo', None)print users# prints{'lastname': 'Smith', 'age': 27, 'firstname': 'John'}

这是删除一堆密钥的单行代码从字典中删除,而不会导致不存在的键出现错误。

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27, 'dob': '15-sep-1971'}map(lambda x : users.pop(x, None),['age', 'foo', 'dob'])print users

是否要从字典中删除所有键?使用 clear()方法。

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}users.clear()print users# prints{}

使用Python字典循环

Python提供了许多用于循环字典条目的方法。选择一个适合您的需求。

  • The simplest method for processing keys (and possibly values) in sequence uses a loop of the form:
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}for k in users:  print k, '=>', users[k]# printslastname => Smithage => 27firstname => John
  • Using the method iterkeys() works exactly the same as above. Take your pick as to which form you want to use.
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}for k in users.iterkeys():  print k, '=>', users[k]# printslastname => Smithage => 27firstname => John
  • A third method to retrieve and process keys in a loop involves using the built-in function iter().
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}for k in iter(users):  print k, '=>', users[k]# printslastname => Smithage => 27firstname => John
  • When you need the index of the key being processed, use the enumerate() built-in function as shown.
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}for index, key in enumerate(users):  print index, key, '=>', users[k]# prints0 lastname => John1 age => John2 firstname => John
  • When you want to retrieve each key-value pair with a single call, use iteritems().
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}for k, v in users.iteritems():  print k, '=>', v# printslastname => Smithage => 27firstname => John
  • The method itervalues() can be used to iterate over all the values in the dictionary. Though this method looks similar to a loop using values(), it is more efficient since it does not extract all the values at once.
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}for value in users.itervalues():  print value# printsSmith27John

    以下方法描述了以数组形式提取各种Python字典信息。可以使用普通的python构造将结果数组进行循环。但是,请记住,根据字典的大小,返回的数组可能会很大。因此,与使用上述迭代器方法相比,处理这些数组可能更昂贵(在内存方面)

    一种可以使用这些数组的情况是当您遇到不想要的元素时需要从字典中删除项目的时候。在修改字典的同时使用迭代器可能会导致RuntimeError。

  • The method items() returns an array of key-value tuples. You can iterate over these key-value pairs as shown:
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}for k, v in users.items():  print k, '=>', v# printslastname => Smithage => 27firstname => John
  • Retrieve all the keys in the dictionary using the method keys().
    users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27}print users.keys()# prints['lastname', 'age', 'firstname']

    使用返回的数组来遍历键。

    for k in users.keys():  print k, '=>', users[k]# printslastname => Smithage => 27firstname => John
  • In a similar way, use the method values() to retrieve all the values in the dictionary.
    for value in users.values():  print value# printsSmith27John

    如何使用Python字典?

  • 标签: