Python dict()函数的用法是甚么
dict()函数用于创建一个字典对象。它有以下几种经常使用的用法:
empty_dict = dict()
print(empty_dict) # {}
person = dict(name='John', age=30, city='New York')
print(person) # {'name': 'John', 'age': 30, 'city': 'New York'}
fruits = dict([('apple', 2), ('banana', 3), ('orange', 5)])
print(fruits) # {'apple': 2, 'banana': 3, 'orange': 5}
colors = dict([['red', 1], ['blue', 2], ['green', 3]])
print(colors) # {'red': 1, 'blue': 2, 'green': 3}
old_dict = {'name': 'John', 'age': 30}
new_dict = dict(old_dict)
print(new_dict) # {'name': 'John', 'age': 30}
需要注意的是,dict()函数在Python 3中也能够用于创建字典推导式,但在此上下文中不会进行讨论。
TOP