#字典
#字典,其实就是键值对存放数据的一种对象
dict1={"A":"apple","B":"book"}
# print(dict1)
#字典是无序的
dict2={"B":"book","A":"apple"}
# print(dict1==dict2)#返回True,相同
# list1=[1,2]
# list2=[2,1]
# print(list1==list2)#返回False
#字典是可变对象,可以进行增删改操作
#增加:通过下标来操作,字典的下标就是键key,如果键不存在就进行新增,如果存在就进行更新
dict2={"A":"apple","B":"book","A":"ace"}
dict2.update({"a":"animal","b":"bike","c":123})
# print(dict2)
# print(id(dict2))
#删除:删除键就可以,因为字典是以键值对存在的,删除键的同时,值也一起删除
# del dict2["a"],dict2["c"]
# del dict2["bike"]#不允许删除值
# print(dict2)
#清空字典
# dict2={}#id不一样,相当于新增了一个新的字典
# print(id(dict2))
#用clear方法清空
# dict2.clear()
# print(id(dict2))
#判断某个键是否位于字典中,用in进行判断,判断的是键,而不是值
# if "ace" in dict2:
# print("在字典中")
# else:
# print("不在字典中")
#字典是可变对象,键能存放哪些类型?可以存放数字,字符串,元祖,不能存放列表和元祖
#值能存放哪些类型?值可以存放任意类型的数据
dict5={1}#这个代表是一个集合,不是字典
print(type(dict5))#<class 'set'>
#遍历字典中的键
# print(type(dict2.keys()))#生成一个类列表<class 'dict_keys'>,可以遍历,但不能用下标,如果需要用下标,需要转成列表
#dict_keys(['A', 'B', 'a', 'b', 'c'])
# print(dict2.keys()[0])#TypeError: 'dict_keys' object does not support indexing
# for one in dict2.keys():
# print(one)
# print(list(dict2.keys())[0])
#遍历字典中的值,也是一个类列表
# for one in dict2.values():
# print(one)
#遍历字典的键和值
# for k,v in dict2.items():
# print(k,v)
import json
import pprint
#json格式非常严格,必须是双引号,不能是单引号(不能转换成字典),不能多字符,也不能少字符
data1='''{
"aac003" : "tom",
"tel" : "13959687639",
"crm003" : "1",
"crm004" : "1"
}'''
# print(type(data1))#<class 'str'>
# print(data1)
# pprint.pprint(data1)
#转换为字典
dict3=json.loads(data1)#josn为单引号报错:json.decoder.JSONDecodeError: Expecting value: line 3 column 13 (char 36)
# pprint.pprint(dict3)
# print(dict3)
# print(type(dict3))
#字典转换为json
# print(type(json.dumps(dict3)))
# print(json.dumps(dict3))#{"aac003": "tom", "tel": "13959687639", "crm003": "1", "crm004": "1"}
# pprint.pprint(json.dumps(dict3))#'{"aac003": "tom", "tel": "13959687639", "crm003": "1", "crm004": "1"}'
# with open("d:/json1.txt") as file1,open("d:/json2.txt","w+") as file2:
# dict4=json.load(file1)#从文件中读取json文件,并转换成字典
# json.dump(dict4,file2)#字典转换成json文件并写入文件中
# file2.seek(0)#光标移到开始位置
# print(file2.read())