【问题标题】:Best way to process the update of dictionary in python在 python 中处理字典更新的最佳方法
【发布时间】:2022-11-27 12:17:09
【问题描述】:

我希望根据我在字典中的值通过循环来更新我的字典,但我的方法很幼稚而且不酷所以我想在这里寻求帮助看看是否有更好的单行或几行处理方式它有相同的输出?

我的代码:

g_keypoints = {"test1": (14,145), "test2": (15, 151)}
d = {}
for k, v in g_keypoints.items():
    d.update({k+"_x":v[0]})
    d.update({k+"_y":v[1]})

我的输出:

{'test1_x': 14, 'test1_y': 145, 'test2_x': 15, 'test2_y': 151}

我的期望: 单行或更好的 pythonize 方式

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    我认为您基本上想要一个使用列表理解的解决方案。

    g_keypoints = {"test1": (14,145), "test2": (15, 151)}
    d = {}
    [(d.update({k+"_x":v[0]}), d.update({k+"_y":v[1]})) for k,v in g_keypoints.items()]
    print(d)
    

    这似乎有效并产生与您相同的输出,尽管我觉得您拥有它的方式使它比使用单行更具可读性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2011-09-23
      • 1970-01-01
      • 2022-01-11
      • 2012-01-15
      • 1970-01-01
      相关资源
      最近更新 更多