Right now, I have this very clunky dictionary:
input_data = {'names': 'Elizabeth,Emily,Grant', 'titles': 'Sales,Accounting,Operations'}
nameList = input_data['names'].split(',')
titleList = input_data['titles'].split(',')
d1 = dict()
d2 = dict()
for val in nameList:
d1.setdefault('Name', []).append(val)
for val in titleList:
d2.setdefault('Title', []).append(val)
fullDict = dict(d1, **d2)
I'm convinced there's a better way to covert this:
{'names': 'Elizabeth,Emily,Grant', 'titles': 'Sales,Accounting,Operations'}
Into this:
{'Name': ['Elizabeth', 'Emily', 'Grant'],
'Title': ['Sales', 'Accounting', 'Operations']}
This simple dictionary comprehension seemed to produce the result you wanted.
{x: y.split(',') for x, y in input_data.items()}
If the name part is also important, then I think this should work.
{x.title()[:-1] if x[-1] == 's' else x.title(): y.split(',') for x, y in input_data.items()}
So you want to accomplish two things: Split the values in the original dictionary, and rename the keys in the original dictionary. You can do everything in-place, as opposed to creating new dictionaries.
input_data = {'names': 'Elizabeth,Emily,Grant', 'titles': 'Sales,Accounting,Operations'}
input_data['Name'] = input_data['names'].split(',')
input_data['Title'] = input_data['titles'].split(',')
del input_data['names'], input_data['titles']
print(input_data)
Returns the output:
{'Name': ['Elizabeth', 'Emily', 'Grant'], 'Title': ['Sales', 'Accounting', 'Operations']}
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.