python

loop a dict to update key

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 cases only exist when prefix is same to a key of the dict. This 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)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s