# __author__:Nzkalhbxx
# __date__:2017/10/15
# fromkeys()方法创建字典,第一个参数为字典中的所有键, 第二个参数无论是什么类型, 都将整体作为每个key的value
dic = dict.fromkeys(['name', 'age'], 'wdq')
print(dic)
dic = dict.fromkeys(['name', 'age'], ['wdq', 19])
print(dic)
# 使用fromkeys()方法创建字典的问题, 在于修改键值时会整体修改
dic['name'][0] = 'psj'
print(dic)
print("\n-------------------------------------".center(37, '-'))
# dic = {'name': 'psj', 3: 'age', 'girl': True}
dic = {'name': 'psj', 'age': '19', 'hobby': 'Passion fruit'}
# 对字典进行排序, 默认是对key进行排序, 默认返回的也是keys
# 注意: 要进行排序的元素必须是类型相同的, 都这会报错
newDic = sorted(dic)
print(newDic)
newDicValue = sorted(dic.values())
print(newDicValue)
newDicKeys = sorted(dic.keys())
print(newDicKeys)
# 对键值对进行排序, 是对key进行排序
newDicItems = sorted(dic.items())
print(newDicItems)
print("\n-----------------遍历字典----------------".center(37, '-'))
# 遍历字典时默认是遍历字典的key, 所以获取的就是字典的key值
for item in dic:
print(item)
print(item, dic[item], sep='->')
print("\n------------遍历字典的key-value-----------".center(37, '-'))
print(dic.items())
for k, v in dic.items():
print(k, v, sep=": ")
运行结果
网友评论