2022年 11月 16日

Python字典推导式

字典推导式和列表推导式有点类似

如 给定一个列表,里面的元素都是长度=2的元组,用推导式的方法生成字典

  1. #字典推导式
  2. arry = [('a',3),('b',4),('c',5)]
  3. dict_ = {key:value for (key,value) in arry}
  4. print(dict)
  5. #结果
  6. {'a': 3, 'b': 4, 'c': 5}

拓展:将字符串以|拆分,并生成字典

  1. #将字符串以竖线拆分,变成字典k:1的形式
  2. str1 = 'k:1|k1:2|k2:3|k3:4'
  3. def dict_func(str1):
  4. dict1 = {}
  5. for item in str1.split('|'):
  6. key,value = item.split(':')
  7. dict1[key] = value
  8. return dict1
  9. print(dict_func(str1))
  10. #结果
  11. {'k': '1', 'k1': '2', 'k2': '3', 'k3': '4'}