Python dict的常用方法示例代码

2020-06-23 12:00 来源:易采站长站 作者:于丽 点击: 评论:

A-A+

原标题:Python dict的常用方法示例代码

常用方法

浅拷贝copy

a = {"ilpy1": {"company": "aaa"},
   "ilpy2": {"company": "bbb"}
   }
new_dict = a.copy()
new_dict["ilpy1"]["company"] = "wtf"
print(new_dict)
print(a)
print(id(a))
print(id(new_dict))
print(id(new_dict["ilpy1"]["company"]))
print(id(a["ilpy1"]["company"]))

然后我们发现,执行这一步操作时new_dict["ilpy1"]["company"] = "wtf",对a也执行了修改,比较id可知new_dict["ilpy1"]["company"]))a["ilpy1"]["company"]指向了同一位置,而anew_dict指向不同位置,这就是浅拷贝的副作用

深拷贝

这并不是dict自带的方法而是来自python的一个包copy

import copy

a = {"ilpy1": {"company": "aaa"},
   "ilpy2": {"company": "bbb"}
   }


new_dict = copy.deepcopy(a)
print(id(a))
print(id(new_dict))
a['ilpy1']['company'] = "666"
print(a)
print(new_dict)

list转换dict

import copy

a = {"ilpy1": {"company": "aaa"},
   "ilpy2": {"company": "bbb"}
   }
myList = ['aaa', 'bbb']
new_dict = dict.fromkeys(myList, "2")
print(new_dict)

items

a = {"ilpy1": {"company": "aaa"},
   "ilpy2": {"company": "bbb"}
   }
for key,value in a.items():
   print(key,value)

clear

a = {"ilpy1": {"company": "aaa"},
   "ilpy2": {"company": "bbb"}
   }
# clear 清楚dict元素
# a.clear()
# print(a)

update

a = {"ilpy1": {"company": "aaa"},
   "ilpy2": {"company": "bbb"}
   }

a.update(a=1,b=2)
print(a)

传入可迭代对象也可

a = {"ilpy1": {"company": "aaa"},
   "ilpy2": {"company": "bbb"}
   }

a.update([('1','2')])
print(a)
a.update((('1','2'),))
print(a)

setdefault

Python 字典 setdefault() 函数和 get()方法 类似, 如果键不存在于字典中,将会添加键并将值设为默认值。所以当我们需要快速判断键值对是否存在并且加上去的时候就可以使用此方法

ps:下面看下python-dict和list常用方法

# *********-list-*********
# 创建一个list
list1 = [1, 2, '力气,', 'afd']
print(type(list1))
print(list1)
# 添加单个元素
list1.append('ffff')
print(list1)
list2 = ['ff2', 34]
# 添加list
list2.extend(list1)
print(list2)
# 获取指定index的元素
print(list2[2])
# 删除指定values元素
list2.remove('value')
# 删除index=2的元素
del list2[2]
print(list2)
# 创建一个list1中的数据重复2次的list3
list3 = list1*2
print(list3)
# 排序
list4 = [1, 2, 8, 3, 12, 3]
# 升序
list4.sort()
print(list4)
# 降序
list4.reverse()
print(list4)
# 创建一个二维数组
list_muti = [[0, 0, 1]]*2
print(list_muti)
print(list_muti[0][1])
# *********-dict-*********
# 创建一个dict
dict1 = {}
print(type(dict1))
# 字典添加元素
dict1['a'] = 'value-a'
print(dict1)
# 批量添加元素
listx = []
for value in ('abced'):
  for key in (['abcde', 're', 1, 'n你re1', 3]):
    if key in listx:
      continue
    else:
      listx.append(key)
      # print(value)
      # print(key)
      dict1[key] = value
      break
print(dict1)
# dict里的fromkeys方法
dict1 = dict1.fromkeys(('a', 'ccc'), """ "nn'n'" """)
print(dict1)
# 获取keys之后转成list显示
keylist = list(dict1.keys())
print('%s' % keylist[0])
# 获取values之后转成list显示
valuelist = list(dict1.values())
print('%s' % valuelist[0])
print(dict1)
# 获取key对应的value
value = dict1['a']
print(value)
value2 = dict1.get('ccc', '木有找到')
# 与dict.get()方法一致,但是如果没有对应的key会自动创建一个key,value为none
dict1.setdefault('m')
print(dict1)
# 更新字典,如果没有对应的key会自动添加key-dict
dict1.update({'ccc': 'fff2'})
print(dict1)
value2 = dict1.get('ccc1', '木有找到')
print(value2)

【易采站长站编辑:秋军】