Loop a dict to update the keys

Posted on July 21, 2016

Source dict:

{'keyA': '', 'keyB': ''}

Expected dict:

{keyA/'keyA' :’’, keyA/keyB : ‘’}

Code1:

keyPrefix = 'keyA'
for key, value in Dict.items():
    newkey = '/'.join([keyPrefix, key])
    Dict[newkey] = Dict.pop(key)

Code2:

keyPrefix = 'keyA'
for key, value in Dict.keys():
    newkey = '/'.join([keyPrefix, key])
    Dict[newkey] = Dict.pop(key)

Result of code1/code2 is:

{'keyA/keyA/keyB' : '', 'keyA/keyA/keyA': ''}

It doesn’t work as expected, and I found the case only exists when prefix is the same to a key of the dict which means code1/code2 works well when the keyPrefix is neither ‘keyA’ nor ‘beyB’.

My way to resolve this unexpected result:

Dict = {'/'.join([keyPrefix, key]): value for key, value in Dict.items()}

For complex case:

keyPrefix = 'keyA'
for key in list(Dict.keys()):
    newkey = '/'.join([keyPrefix, key])
    Dict[newkey] = Dict.pop(key)

Loop a dict to update the keys


donation

Scan the QR code using WeChat

comments powered by Disqus