【问题标题】:Looping through 2 dictionaries in python在python中循环遍历2个字典
【发布时间】:2017-10-13 16:36:34
【问题描述】:

我是 Python 新手,所以我没有太多经验,如果这是一个愚蠢的问题,请见谅。

我正在读取一堆 Json 文件并将一些值存储到 2 个单独的字典中。我正在尝试将结果输出如下: ID、现名、首名 但我不确定如何在一个 for 循环中浏览两个字典。到目前为止,我有以下内容:

for dev, dev2 in zip(current.items(), initial.items()):
    print(dev, dev2, sep=",")

字典的名称是 currentinitial 。然而,这个输出是重复 ID,所以我有: (ID, [current]) , (ID, [initial]) 并且格式有一些随机的 unicode 字符,所以我不知道如何解决这个

任何帮助将不胜感激!

这是完整的代码:(我有 Python 2.7.10 btw)

from __future__ import print_function
import json
import os

import io
import shutil

current = {}
initial = {}

for file in os.listdir('.'):
    if not ".json" in file:
        continue

    data = io.open(file, 'r', encoding="utf8")

    commit = json.load(data)

    for branch in commit["branches"]:
        for change in branch["methodChanges"]:
            method_name = change["methodProperties"]["name"]
            change_type = change["methodChangeProperties"]["changeOperation"]

            if method_name in current:
                current[method_name].append(commit["committer"])
            else:
                current[method_name] = [commit["committer"]]


            if change_type == "ADDED":
                initial[method_name] = commit["committer"]


print("Method","Current Developer","Initial Developer", sep=",")

#for dev in current:
    #print(dev, current[dev], sep=",")
#for dev2 in initial:
    #print(dev2, initial[dev2], sep=",")

for dev, dev2 in zip(current.items(), initial.items()):
    print(dev, dev2, sep=",")

最后注释的 for 循环中的每个打印函数都单独工作,但我试图通过匹配第一个字段将两个输出组合在一个表中。我想要得到的输出是一个 ID 为 (称为名称)、Current、Initial

的表

【问题讨论】:

  • 目前还不清楚您期望什么输出。字典没有排序,所以压缩它们没有什么意义。
  • 从发布您的字典开始当前和初始
  • @jonrsharpe 他们从 python 3.6 开始;)
  • 如果你只关心idname 字段,你为什么还要循环呢?只需直接在两个字典中访问这些字段。
  • @Y0da 他们仍然没有语义排序;参见例如stackoverflow.com/q/39980323/3001761,它被认为是一个实现细节。

标签: python json for-loop


【解决方案1】:

你可以使用一个字典来引用另一个

for k, v in initial,items():
    from_other_dict = current.get(k,'')
    print(k, v, ','.join(from_other_dict), sep=",")

【讨论】:

  • 这似乎有效但是知道如何摆脱 unicode 格式的输出吗?示例输出: 146783,bodewig,[u'damjan', u'damjan'] 有没有办法在没有 u' ' 的情况下显示?再次感谢
  • @Omar 立即尝试
猜你喜欢
  • 2023-03-12
  • 2022-09-22
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2023-04-03
  • 2014-06-26
  • 2019-09-02
相关资源
最近更新 更多