当前位置:   article > 正文

python 学习之:字典默认值的用法

字典默认值

默认值

从字典中读取时使用默认值

dic = {"a":1,"b":2, "c":3, "d":4}

key = "e"
value = 0
if key in dic:
    value = dic[key]
else:
    value = 0

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
value = dic.get("e",0)
# 同时也可以将列表作为默认值
value2 = dic.get("e",[1,2,3])
  • 1
  • 2
  • 3
value
  • 1
0
  • 1
value2
  • 1
[1, 2, 3]
  • 1

创建字典时使用默认值

words = ["apple","banana","airline","bank","panda"]
by_letters = dict()

  • 1
  • 2
  • 3
for word in words:
    first_letter = word[0]
    if first_letter in by_letters:
        by_letters[first_letter].append(word)
    else:
        by_letters[first_letter] = [word]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
by_letters
  • 1
{'a': ['apple', 'airline'], 'b': ['banana', 'bank'], 'p': ['panda']}
  • 1

setdefault 方法

by_letters = {}
for word in words:
    by_letters.setdefault(word[0],[]).append(word)
  • 1
  • 2
  • 3
by_letters
  • 1
{'a': ['apple', 'airline'], 'b': ['banana', 'bank'], 'p': ['panda']}
  • 1

collection 中的 defaultdict

from collections import defaultdict
by_letters = defaultdict(list)
for word in words:
    by_letters[word[0]].append(word)
  • 1
  • 2
  • 3
  • 4
by_letters
  • 1
defaultdict(list,
            {'a': ['apple', 'airline'],
             'b': ['banana', 'bank'],
             'p': ['panda']})
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/515663
推荐阅读
相关标签
  

闽ICP备14008679号