简体   繁体   中英

How to update key and value name in dictionary using for loop in python?

I have a dictionary like this

{'sub_type': 'additive', 'data_type': 'Number', 'value': False, 'field_type': 'measure'}

I need to iterate through key, value pairs and change the key and value name,

for example

if key=='sub_type',

the key name should get updated to " type ", and

if value== 'additive', 

the value name should get updated to " add "

Iterating-and-updating a mapping is pretty gnarly and Python certainly has no support specifically for that, especially when you want to update not just the values but the keys as well: that translates to changing the internal layout of the dictionary on the fly, which affects the order of iteration for instance (you'd pop() each key and reinsert whatever replacement made sense, but then depending on the mapping you might have the issue of trying to replace keys you had not popped yet resulting in inconsistent behaviour).

Technically possible but generally a very bad idea.

The better approach is usually to just create a new dict from the old one eg

transformed = dict(
    (
        "type" if key == "sub_type" else key,
        "add" if value == "additive" else value
    )
    for key, value in original.items()
)

Although for the specific case where you want to replace one (key, value) pair if it's present, you can just pop() the offending key then reinsert the replacement eg

if val := original.pop("sub_type", None):
    # convert additive to add, leave other types as-is
    if val = "additive":
        val = "add"
    original["type"] = val

You can simply do this:

rename key:

In [1626]: d = {'sub_type': 'additive', 'data_type': 'Number', 'value': False, 'field_type': 'measure'}

In [1628]: d['type'] = d.pop('sub_type')

rename value:

In [1630]: for k,v in d.items():
      ...:     if v == 'additive':
      ...:         d[k] = 'add'
      ...: 

Output:

In [1631]: d
Out[1631]: {'data_type': 'Number', 'value': False, 'field_type': 'measure', 'type': 'add'}

Try this:

for key, value in d.items():
    if key =='sub_type' and value == 'additive':
        d[key] = 'add'
        d["type"] = d.pop(key)
    else:
        break

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