【问题标题】:Fastest way to get values from dictionary to another dictionary in python without using if?在不使用if的情况下从字典中获取值到python中另一个字典的最快方法?
【发布时间】:2021-06-26 14:54:08
【问题描述】:

我需要找到一种方法从一个字典获取值到另一个字典,基于键名匹配而不使用两个循环 \if 语句。

主要目标是让它更高效地运行,因为它是更大代码的一部分并在多个线程上运行。

如果你能保持字典结构会有所帮助

第二个字典在高级中用值 0 初始化

dict_1 = {
    "school": {
        "main": ["first_key"]
    },
    "specific": {
        "students": [
            {
                "name": "sam",
                "age": 13
            },
            {
                "name": "dan",
                "age": 9
            },
            {
                "name": "david",
                "age": 20
            },
            {
                "name": "mike",
                "age": 5
            }
        ],
        "total_students": 4
    }
}

dict_2 = {'sam': 0, 'mike': 0, 'david': 0, 'dan': 0, 'total_students': 0}

for i in dict_1["specific"]['students']:
    for x in dict_2:
        if x == i["name"]:
            dict_2[x] = i["age"]

    dict_2["total_students"] = dict_1["specific"]["total_students"]

print(dict_2)

还有更优雅的方法吗?

谢谢!!

【问题讨论】:

    标签: python loops dictionary if-statement


    【解决方案1】:

    您根本不需要两个循环!你甚至不需要提前初始化dict_2。只需循环 dict_1["specific"]["students"] 并将年龄分配给 dict_2 而不使用 if。

    for student in dict_1["specific"]["students"]:
        student_name = student["name"]
        student_age = student["age"]
        dict_2[student_name] = student_age
    

    你也可以这样写:

    dict_2 = {student["name"]: student["age"] for student in dict_1["specific"]["students"]}
    

    这两个都给出以下dict_2:

    {'sam': 13, 'dan': 9, 'david': 20, 'mike': 5}
    

    然后你可以像你已经做的那样设置dict_2["total_students"],但在任何循环之外。

    dict_2["total_students"] = dict_1["specific"]["total_students"]
    

    如果您只想为dict_2 中的学生分配年龄,则需要if。但是,您仍然可以使用单个循环而不是两个循环来执行此操作。 :

    for student in dict_1["specific"]["students"]:
        student_name = student["name"]
        if student_name not in dict_2:
            continue # skip the rest of this loop
    
        student_age = student["age"]
        dict_2[student_name] = student_age
    

    这两种方法都使用单循环,因此它们会比双循环方法更快。

    【讨论】:

      【解决方案2】:
      for i in dict_1['specific']['students']:
       dict_2[i['name']]=i['age']
      
      dict_2['total_students']=dict_1['specific']['total_students']
      

      在 O(N) 时间和 O(N) 空间中运行。 你目前在 O(N^2) 时间和 O(N) 空间中运行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-07
        • 1970-01-01
        • 2022-07-10
        相关资源
        最近更新 更多