簡體   English   中英

如何迭代 2 JSON 列表(混合字典和列表),匹配特定值並打印另一個值

[英]How do I iterate over 2 JSON lists (mix dict and list), match specific values and print another value

我有 2 個單獨的 JSON 列表(帶有字典)。 我的目標是,我想遍歷 list2“currentUser”,獲取值,在 list1 中搜索這些值,然后 output 打印“firstName”的值

例如 liste2: "currentUser": 123, liste1: "id": "123", --> "firstName": "Lisa",

list1 = {
    "X-API-KEY": "XyZzahZaksksXXXYYYOOO000",
    "user": {
                "email": "Lisa@BLA.com",
                "firstName": "Lisa",
                "id": "123",
    },
    "Flat": {
        "city": "Munich",
        "country": "2",
        "countryCode": "DEU",
        "currency": "EUR",
        "date": "1587671397",
        "flatmates": [
            {
                "email": "Lisa@BLA.com",
                "firstName": "Lisa",
                "id": "123",
            },
            {
                "email": "Max@BLA.com",
                "firstName": "Max",
                "id": "124",
            },
            {
                "email": "Hannah@BLA.com",
                "firstName": "Hannah",
                "id": "125",
            },
            {
                "email": "Kai@BLA.com",
                "firstName": "Kai",
                "id": "126",
            }
        ],
        "founderId": "123",
        "id": "99999",
        "image": "",
        "name": "ABC",
        "postCode": "000000",
    }
}
list2 = [
    {
        "creationDate": 1587671663,
        "currentUser": 123,
        "id": 1717134,
        "title": "Do this",
        "users": [
            124,
            126
        ]
    },
    {
        "creationDate": 1587671663,
        "currentUser": 126,
        "id": 1717134,
        "title": "Do that",
        "users": [
            123,
            125
        ]
    },
    {
        "creationDate": 1587671821,
        "currentUser": 124,
        "id": 1717134,
        "title": "Clean this",
        "users": [
            125,
            122
        ]
    },
    {
        "creationDate": 1587671801,
        "currentUser": 123,
        "id": 1717134,
        "title": "Clean that",
        "users": [
            124,
            126
        ]
    }
]

我是 python 的新手。我有幾個頭腦問題,因為它混合了列表和字典,以及如何匹配/搜索 2 個單獨的列表/字典的值

到目前為止我得到了什么:迭代“CurrentUser”

for user in liste2:
    print(user["currentUser"])

有沒有人有一些方法?

在沒有其他模塊的純 python 中。

for user in list2:
    for mate in list1['Flat']['flatmates']:
        if user['currentUser'] == int(mate['id']):
            # You found the person now execute this code...

需要注意的一件事是,在您的 list1 中,您的室友 ID 不是 integer 而是一個字符串。 因此,您必須將其轉換為 int 才能比較兩者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM