Skip to main content
 首页 » 编程设计

python之创建动态 Python 字典引用路径

2025年05月04日8lonelyxmas

我在动态创建 Python 字典路径以循环遍历和验证值时遇到问题。这是我想做的:

使用 Requests 1.0 进行 API 调用并将 JSON 响应存储在字典中。

response = requests.get(path/to/file.json).json() 

response 对象的格式如下:

{    
"status": "OK", 
"items": [ 
    { 
        "name": "Name 1", 
        "id": 0, 
        "address":{ 
            "city": "New York", 
        } 
    }, 
    { 
        "name": "Name 2", 
        "id": 1, 
        "address":{ 
            "city": "New York", 
        } 
    }, 
    { 
        "name": "Name 3", 
        "id": 2, 
        "address":{ 
            "city": "New York", 
        } 
    }] 
} 

将response 字典、field 和value 发送到函数进行验证。该函数将采用响应对象并将字段条目附加到它以定义其路径,然后根据值进行验证。所以理论上应该是:

response[field] = value 

我为此编写的代码是:

def dynamic_assertion(response, field, value): 
        i = 0 
        stations = "response['items']" 
        count = len(response['items']) 
        while i < count: 
            path = '%s[%s]%s' % (stations, i, field) 
            path = path.strip("") 
            if path != value: 
                print type(path) 
                return False 
            i += 1 
        return True 
 
dynamic_assertion(response, "['address']['city']", "New York") 

我意识到,一旦我创建了路径字符串,它就不再是一个对象。如何以允许我保留响应对象并附加要遍历的引用路径的方式创建它?这可能吗?!

请您参考如下方法:

我认为您最好避免使用单个 path 字符串,而使用表示嵌套字典中各个键的元组或字符串列表。也就是说,而不是 ['address']['city']" 作为你的 field 参数,你会传递 ("address", "city ")。然后你只需要一个循环来遍历键并查看最终值是否正确:

def dynamic_assertion(response, field, value): 
    for item in response["items"]: 
        for key in field: 
            item = item[key] # go deeper into the nested dictionary 
        if item != value: 
            return False # raising an exception might be more Pythonic 
    return True 

示例输出(给定问题中的response dict):

>>> dynamic_assertion(response, ("address", "city"), "New York") 
True 
>>> dynamic_assertion(response, ("address", "city"), "Boston") 
False 
>>> response["items"][2]["address"]["city"] = "Boston" # make response invalid  
>>> dynamic_assertion(response, ("address", "city"), "New York") 
False 
>>> dynamic_assertion(response, ("address", "city"), "Boston") 
False