简体   繁体   中英

How to change value in a dict?

I have so many dict data with different formats and I want to change the key place to None. I create this function to read all value, but I can change it

def test(T, data):
    if T:
        T.pop(0)
    for cle, valeur in data.items():
        if isinstance(valeur, dict):
            T.append(valeur)
        elif isinstance(valeur, list):
            for idx, obj in enumerate(valeur):
                if isinstance(obj, dict):
                    T.append(obj)
        else:
            print(cle, valeur)
    if T:
        test(T, T[0])
test(T=[], data=datas)

example data:

datas={
"first_name": "test",
"last_name": "test",
"cars": [
    {"mark": "test", "type": "12"},
    {"mark": "test2", "type": "7"},
],
"date_created": "2022-05-07",
"invoice_info": {
    "price": 1233,
    "currency": "EUR",
    "total": {"product1": 12, "product2": 22},
    "date": [
        {"date_1": "2022-05-07", "info": {"comment": "test", "place": "France"}},
        {"date_2": "2022-06-12", "info": {"comment": None, "place": "France"}},
    ]

}

}

You can do

key = 'yourkey'
dic[key] = new_value

Basically you just tell python that the value for the associated key is now new_value .

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