Dictionary用于在python中实现键值对。字典是python中的数据类型,它可以模拟真实数据排列,其中某些特定键存在某些特定值。
换句话说,我们可以说字典是键值对的集合,其中值可以是任何python对象,而键是不可变的python对象,即Numbers,string或tuple。
字典在python中模拟Java哈希映射。
创建字典
可以使用小括号()括起来并用冒号(:)分隔的多个键值对来创建字典。键值对的集合包含在花括号{}中。
下面给出了定义字典的语法。
Dict = {"Name": "Ayush","Age": 22}
在上面的字典Dict中,键名称和Age是作为不可变对象的字符串。
让我们看一个创建字典并打印其内容的示例。
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
输出:
<class 'dict'>
printing Employee data ....
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}
访问字典值
我们已经讨论了如何使用索引在列表和元组中访问数据。
但是,可以使用键在字典中访问值,因为键在字典中是唯一的。
可以通过以下方式访问字典值。
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
输出:
<class 'dict'> printing Employee data .... Name : John Age : 29 Salary : 25000 Company : GOOGLE
Python为我们提供了使用get()方法访问字典值的替代方法。它将给出索引给出的相同结果。
更新字典值
字典是可变数据类型,可以使用特定键更新其值。
让我们看一个更新字典值的示例。
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
输出:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'salary': 25000, 'Company': 'GOOGLE', 'Age': 29}
Enter the details of the new employee....
Name: David
Age: 19
Salary: 8900
Company:JTP
printing the new data
{'Name': 'David', 'salary': 8900, 'Company': 'JTP', 'Age': 19}
使用del关键字删除元素
可以使用下面给出的del关键字删除字典的项目。
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
输出:
<class 'dict'>
printing Employee data ....
{'Age': 29, 'Company': 'GOOGLE', 'Name': 'John', 'salary': 25000}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
Traceback (most recent call last):
File "list.py", line 13, in <module>
print(Employee)
NameError: name 'Employee' is not defined
迭代字典
可以使用如下给出的for循环来迭代字典。
例1
#for循环打印字典的所有键
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(x);
输出:
Name Company salary Age
例2
#for循环打印字典的所有值
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(Employee[x]);
输出:
29 GOOGLE John 25000
例3
#for循环使用values()方法打印字典的值。
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.values():
print(x);
输出:
GOOGLE 25000 John 29
例4
#for循环使用items()方法打印字典的项目。
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.items():
print(x);
输出:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
字典键的属性
1.在字典中,我们不能为相同的键存储多个值。如果我们为单个键传递多个值,则最后分配的值将被视为键的值。
请考虑以下示例。
Employee = {"Name": "John", "Age": 29, "Salary":25000,"Company":"GOOGLE","Name":"Johnn"}
for x,y in Employee.items():
print(x,y)
输出:
Salary 25000 Company GOOGLE Name Johnn Age 29
2.在python中,键不能是任何可变对象。我们可以使用数字,字符串或元组作为键,但我们不能使用像列表中的任何可变对象作为字典中的键。
请考虑以下示例。
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
for x,y in Employee.items():
print(x,y)
输出:
Traceback (most recent call last):
File "list.py", line 1, in
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'
内置字典功能
下面给出了内置的python字典方法以及描述。
| SN |
功能 |
描述 |
| 1 | cmp(dict1,dict2) |
它比较两个字典的项目,如果第一个字典值大于第二个字典,则返回true,否则返回false。 |
| 2 | len(dict) |
它用于计算字典的长度。 |
| 3 |
str(dict) |
它将字典转换为可打印的字符串表示形式。 |
| 4 |
Type(variable) |
它用于打印传递的变量的类型。 |
内置字典方法
下面给出了内置的python字典方法以及描述。
| SN |
方法 |
描述 |
| 1 |
dic.clear() |
它用于删除字典的所有项目。 |
| 2 |
dict.copy() |
它返回字典的浅表副本。 |
| 3 |
dict.fromkeys(iterable,value = None,/) |
从iterable创建一个新的字典,其值等于value。 |
| 4 |
dict.get(key,default =“None”) |
它用于获取为传递的键指定的值。 |
|
5 |
dict.has_key(Key) |
如果字典包含指定的键,则返回true。 |
| 6 |
dict.items() |
它将所有键值对返回为元组。 |
| 7 |
dict.keys() |
它返回字典的所有键。 |
| 8 |
dict.setdefault(key,default
=“None”) |
如果未在字典中指定密钥,则将其用于将密钥设置为默认值 |
| 9 |
dict.update(dict2) |
它通过将dict2的键值对添加到此字典来更新字典。 |
| 10 |
dict.values() |
它返回字典的所有值。 |
| 11 |
len() |
|
| 12 |
popItem() |
|
| 13 |
pop() |
|
| 14 |
count() |
|
| 15 |
index() |
第1章 Python简介
