#Lists generated from User input.
user1_name = ['Adam']
user1_passion = ['Coding','Wood Chopping','Sleeping']
user2_name = ['Eve']
user2_passion = ['Coding','Eating Apples','Sleeping']
How do I convert the above to a nested dictionary like this?
user_info = {
'user1': {
'fname': 'adam',
'passion': ['coding', 'wood chopping', 'sleeping']
},
'user2': {
'fname': 'eve',
'passion': ['coding', 'eating apples', 'sleeping']
},
}
CodePudding user response:
It's possible to wrangle these lists into a dict by doing something like:
>>> user_info = {
... f"user{i}": {
... 'fname': name[0].lower(),
... 'passion': [p.lower() for p in passion]
... } for i, (name, passion) in enumerate(
... [(user1_name, user1_passion), (user2_name, user2_passion)],
... 1
... )
... }
>>>
>>> user_info
{'user1': {'fname': 'adam', 'passion': ['coding', 'wood chopping', 'sleeping']}, 'user2': {'fname': 'eve', 'passion': ['coding', 'eating apples', 'sleeping']}}
It would be much simpler if these pieces of input weren't in different statically-named variables in the first place though; the easy solution is to just insert them into a dictionary (or list) as you gather the input.
For example:
>>> num_users = 2
>>> user_info = {
... f"user{i}": {
... 'fname': input("User name: ").lower(),
... 'passion': input("What are your passions? (Comma-separated list.) ").lower().split(",")
... } for i in range(1, num_users 1)
... }
User name: Adam
What are your passions? (Comma-separated list.) Coding,Wood Chopping,Sleeping
User name: Eve
What are your passions? (Comma-separated list.) Coding,Eating Apples,Sleeping
>>> user_info
{'user1': {'fname': 'adam', 'passion': ['coding', 'wood chopping', 'sleeping']}, 'user2': {'fname': 'eve', 'passion': ['coding', 'eating apples', 'sleeping']}}