遍历字典列表并保存重复数据

时间:2019-04-11 17:59:43

标签: python python-3.x list dictionary

我想遍历字典列表,并保存某些键(在我的情况下为“ consumer Key”和“ consumer Secret”)的值,因为它们多次出现在另一本词典中。

问题:我可以遍历列表,但是我的代码没有保存第二个使用者密钥和使用者秘密,而是将第一个使用者密钥和使用者秘密保存了两次。

输入:

{
    "accessType": "",
    "apiProducts": [],
    "appFamily": "default",
    "appId": "ac56c8b2-6ac1-4971-a1d3-4bf97893c067",
    "attributes": [
        {
            "name": "DisplayName",
            "value": "quotaapp"
        },
        {
            "name": "Notes",
            "value": ""
        }
    ],
    "callbackUrl": "",
    "createdAt": 1549274952045,
    "createdBy": "suraj.pai.airody@sap.com",
    "credentials": [
        {
            "apiProducts": [
                {
                    "apiproduct": "apiprod",
                    "status": "approved"
                }
            ],
            "attributes": [],
            "consumerKey": "xyz",
            "consumerSecret": "abc",
            "expiresAt": -1,
            "issuedAt": 1549274952051,
            "scopes": [],
            "status": "approved"
        },
        {
            "apiProducts": [
                {
                    "apiproduct": "ouathTest-Product",
                    "status": "approved"
                }
            ],
            "attributes": [],
            "consumerKey": "pqr",
            "consumerSecret": "wmn",
            "expiresAt": -1,
            "issuedAt": 1554802431452,
            "scopes": [],
            "status": "approved"
        }
    ],
    "developerId": "xyz",
    "lastModifiedAt": 1554802431662,
    "lastModifiedBy": "suraj.pai.airody@sap.com",
    "name": "quotaapp",
    "scopes": [],
    "status": "approved"
}

代码:

import requests
import json
from requests.auth import HTTPBasicAuth
import csv


def get_v2details():
    a = 'orgID1'
    b = 'appID1'
    c = 'ConKey1'
    d = 'ConSecret1'
    e = 'appName1'
    org_lst = []
    some_dict = {}
    con_blst = []  # variable to append the dictionary app level
    n = int(input("Enter number of orgs from Landscape 1: "))
    for i in range(0, n):
        ele = str(input())
        org_lst.append(ele)
    cmp_orglst = list(org_lst)
    print(cmp_orglst)
    for j in cmp_orglst:
        url = "https://canarydevmgmtsrv.dmzmo.sap.corp/v1/o/" + str(j) + "/apps/"
        headers = {'Content-Type': 'application/json'}
        response = requests.get(url, auth=HTTPBasicAuth('xyz', 'xyz'), headers=headers, verify=False)
        app_data = json.loads(response.text)
        print(app_data)
        for k in app_data:
            url1 = "https://canarydevmgmtsrv.dmzmo.sap.corp/v1/o/" + str(j) + "/apps/" + str(k)
            headers = {'Content-Type': 'application/json'}
            response1 = requests.get(url1, auth=HTTPBasicAuth('xyz', 'xyz'), headers=headers, verify=False)
            consumer_data = json.loads(response1.text)
            print(" Consumer Data is ", consumer_data)
            for l in range(len(consumer_data['credentials'])):
                some_dict[a] = str(j)
                some_dict[b] = consumer_data['appId']
                some_dict[e] = consumer_data['name']
                some_dict[c] = consumer_data['credentials'][0]['consumerKey']
                some_dict[d] = consumer_data['credentials'][0]['consumerSecret']
                print(some_dict)  # Print dictionary of each app ID
                con_blst.append(some_dict.copy())
            print(con_blst)

            csv_columns = ['orgID1', 'appName1', 'appID1', 'ConKey1', 'ConSecret1']
            csv_file = "Names1.csv"
            try:
                with open(csv_file, 'w', newline='') as csvfile:
                    writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
                    writer.writeheader()
                    for data in con_blst:
                        writer.writerow(data)
            except IOError:
                print("I/O error")

预期结果:

orgID1         appName1         appID1         ConKey1      ConSecret1
VALIDATE    quotaapp    4bf97893c067   xyz           abc
VALIDATE    quotaapp        4bf97893c067    pqr          wmn

实际结果:

orgID1         appName1         appID1         ConKey1      ConSecret1
VALIDATE    quotaapp    4bf97893c067   xyz           abc
VALIDATE    quotaapp        4bf97893c067    xyz          abc

1 个答案:

答案 0 :(得分:0)

看来您只是犯了一个小错误。

        for l in range(len(consumer_data['credentials'])):
            some_dict[a] = str(j)
            some_dict[b] = consumer_data['appId']
            some_dict[e] = consumer_data['name']
            some_dict[c] = consumer_data['credentials'][0]['consumerKey']   #this line
            some_dict[d] = consumer_data['credentials'][0]['consumerSecret'] #and this line
            print(some_dict)  # Print dictionary of each app ID
            con_blst.append(some_dict.copy())

应该是

        for l in range(len(consumer_data['credentials'])):
            some_dict[a] = str(j)
            some_dict[b] = consumer_data['appId']
            some_dict[e] = consumer_data['name']
            some_dict[c] = consumer_data['credentials'][l]['consumerKey']    # Here
            some_dict[d] = consumer_data['credentials'][l]['consumerSecret'] # Here
            print(some_dict)  # Print dictionary of each app ID
            con_blst.append(some_dict.copy())

您没有遍历consumer_data['credentials'],只是存储了consumer_data['credentials'][0]两次