字典的遍历取值以及转换,常用函数的使用

取值

dic1 = {'color': 'red', 'age': 38}
    #获取key
for k in dic1.keys():
    print(k)
    # 获取values
for v in dic1.values():
    print(v)
    # 遍历字典
for k,v in dic1.items():
    print(k,v)
    print("key:"+k,"values:"+str(v))
    #遍历结果为元组
for i in dic1.items():
    print(i)

列表化

print(list(dic1.keys()))
输出为:['color', 'age']

取age键的值,找不到的话使用默认值99

print(dic1.get('age',99) )
输出为:38

如果name键不存在的话,增加并赋默认值;否则不变

dic1.setdefault('name','zx')
输出为:{'color': 'red', 'age': 38, 'name': 'zx'}

如果appl键不存在的话,增加并赋值;否则修改为新值

dic1['appl']=31
输出为:{'color': 'red', 'age': 38, 'name': 'zx', 'appl': 31}

添加多个元素,如已存在,则赋新值

dic1.update({'col1':'face','col2':'eyes'})
输出为:{'color': 'red', 'age': 38, 'name': 'zx', 'appl': 31, 'col1': 'face', 'col2': 'eyes'}

mydict = {'a': 6.18, 'b': 'str', 'c': True}
print('A value: %.2f' % mydict['a'])
mydict['a'] = 523
print(mydict)
print('A value: %d' % mydict['a'])
print('keys: %s' % mydict.keys())
print('values: %s' % mydict.values())
print(mydict.values())

使用范例

字符统计
message = 'It was a bright cold day today, and the colocks where striking thirteen'
count = {}
for character in message:
    count.setdefault(character, 0)
    count[character] = count[character] + 1
print(count)
import pprint
# 美化输出
pprint.pprint(count)
print(pprint.pformat(count))

字典嵌套字符统计

列表和字典可以忽略缩进规则,跨多行
allguests = {'Alice': {'apples': 5, 'pretzels': 13},
             'Bob': {'pears': 3, 'apples': 9},
             'Carol': {'cups': 8, 'pears': 4}}


def totalBrought(guests, item):
    numBrought = 0
    for k, v in guests.items():
        numBrought = numBrought + v.get(item,0)
    return numBrought


print('Number of things being brought:')
print(' - apples ' + str(totalBrought(allguests, 'apples')))
print(' - pears ' + str(totalBrought(allguests, 'pears')))


不要害怕告别,要相信,四季更替,花开花落,都是命中注定。