简体   繁体   中英

python 310 build dynamic url query dict from json response

How can I return a subset of the data dictionary with dict comprehension?

for example

from urllib.parse import urlencode, urlparse

data = [{"id": 123, "description": "big one", "productId": 1}, {"id":124, "description": "medium one", "productId": 2}, {"id": 125, "description": "small one", "productId": 3}]

url = urlparse("https://example.api.com/")
for elem in data:
    query = urlencode(
        query={"description": elem.get("description"), "productId": elem.get("productId")}
    )
    path = f"v1/product/{elem['id']}"
    newurl = url._replace(path=path, query=query)
    logger.debug(newurl.geturl())

My question is poorly worded. I was hoping to get a subset of a dictionary using keys. Answer is here: Extract subset of key-value pairs from dictionary?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM