#用户输入生成列表
user1_name = ['Adam']
user1_passion = ['Coding','Wood Chopping','Sleeping']
user2_name = ['Eve']
user2_passion = ['Coding','Eating Apples','Sleeping']
我如何将上面的转换为像这样的嵌套字典?
user_info = {
'user1': {
'fname': 'adam',
'passion': ['coding', 'wood chopping', 'sleeping']
},
'user2': {
'fname': 'eve',
'passion': ['coding', 'eating apples', 'sleeping']
},
}
可以将这些列表整理成字典,方法如下:
>>> 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']}}
如果这些输入片段一开始就不在不同的静态命名变量中,那就简单多了;简单的解决方案是在收集输入时将它们插入字典(或列表)。
例如:
>>> 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']}}