【问题标题】:Dictionaries and keys字典和键
【发布时间】:2019-05-28 01:18:00
【问题描述】:

这是问题:

用诸如

之类的值创建一个字典
(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.")

【问题讨论】:

  • 问题是什么?我没找到。
  • 嗨,欢迎来到 Stackoverflow。请为每个子问题提供您自己的解决方案。然后我们就可以给你建议,而不是回答你的硬件。
  • 1)d[key] = value 2) 使用ordered_dict, 3) if x in d, 0) fill: {k : v for v,k in enumerate("1234567890")}跨度>

标签: python python-3.x


【解决方案1】:

第一个问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多