Search code examples
pythondictionaryformattingkeynames

Split a full name in an existing dictionary key into new dictionary keys(title, first, etc.) with similar key-names


I have the code finished for organizing the name. I just need help storing the information.

Here is an example dictionary:

{
'FriendName' : 'John Jo Johnson', 
'MomName' : 'Dr. Mom Oclock', 
'DadName': 'Dad Oclock Jr.', 
'BossName: Captain Boss Octopus'}

I need to keep the original key and make 5 new keys for each entry. For example:

'FriendName' : 'John Jo Johnson' needs to generate these 5 new dictionary entries and keep the original entry intact:

'FriendName_Title': "",
'FriendName_First': 'John',
'FriendName_Middle': 'Jo',
'FriendName_Last': 'Johnson',
'FriendName_Suffix': ""

This code will be used on 10s of 1000s of names and all the other names need to follow the same format of:

original_key_name + new designation

I don't have a clue how to copy the original key name from the existing dictionary or save it as a variable. Can someone please explain it to me?


Solution

  • You can extract the original key name as a string using iteritems() which will also give you access to the corresponding dictionary values. string.split() will break your value string into a list that you can access individually for each new entry.

    names = {
        'FriendName' : 'John Jo Johnson', 
        'MomName' : 'Dr. Mom Oclock', 
        'DadName': 'Dad Oclock Jr.', 
        'BossName': 'Captain Boss Octopus'
    }
    
    names_breakdown = {}
    for k, v in names.iteritems():
        s = v.split()
        names_breakdown[k+'_Title'] = ''
        names_breakdown[k+'_First'] = s[0]
        names_breakdown[k+'_Middle'] = s[1]
        names_breakdown[k+'_Last'] = s[2]
        names_breakdown[k+'_Suffix'] = ''
    
    print names_breakdown