字典和键

时间:2019-05-28 01:18:00

标签: python python-3.x

这是问题:

使用诸如

的值创建字典
(1: a, 2:b , 3:c 4:d)

编写Python脚本以将密钥添加到字典。 编写Python脚本以按值对字典进行排序(升序和降序)。 编写Python脚本来检查字典中是否已存在给定键

dictionary = {
    "a":1,
    "b":2,
    "c":3,
    "d":4,
    "e":5,
    "f":6,
    "g":7,
    "h":8,
    "i":9,
    "j":10
    }
print (dictionary)
def is_key_present(x):
    if x in d:
        print ("key is present in the dictionary.")
    else:
        print ("key is not present in the dictionary.")

1 个答案:

答案 0 :(得分:0)

第一个问题:

import operator
dictionary = {
    "a": 3,
    "b": 2,
    "c": 1,
    "d": 4,
    "e": 5,
    "f": 6,
    "g": 7,
    "h": 8,
    "i": 9,
    "j": 10
}

sorted_asc = sorted(dictionary.items(), key=operator.itemgetter(1))
print(sorted_asc)

第二个问题:

def key_in(key, dic):
    rett = False
    if key in dic:
        rett = True
    return rett