You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从列表生成指定结构的动态嵌套Python字典?

Generate Dynamic Nested Dictionary from User List

Got it, let's solve this problem where you need to create a nested dictionary using elements from an input list as the outer keys—each mapped to a fixed preference structure with all values set to 0.

Quick Solution with Dictionary Comprehension

The most concise way to do this in Python is using a dictionary comprehension. Just make sure to copy the inner preference dictionary for each user—this avoids accidental shared references between entries (more on that later!).

def create_user_preferences(user_list):
    # Define the fixed inner preference structure
    base_preferences = {'preference1': 0, 'preference2': 0, 'preference3': 0, 'preference4': 0}
    # Build the outer dictionary by iterating over the user list
    return {user: base_preferences.copy() for user in user_list}

How to Use It

Test with your example list:

user_list = ['user1', 'user2', 'user3']
preference_dict = create_user_preferences(user_list)

# Output the result
print(preference_dict)

This will produce exactly the structure you want:

{
    'user1': {'preference1': 0, 'preference2': 0, 'preference3': 0, 'preference4': 0},
    'user2': {'preference1': 0, 'preference2': 0, 'preference3': 0, 'preference4': 0},
    'user3': {'preference1': 0, 'preference2': 0, 'preference3': 0, 'preference4': 0}
}

Why copy() Matters

If you skip the copy() and just assign base_preferences directly, every user entry will point to the same inner dictionary. That means if you update preference_dict['user1']['preference1'] = 5, all other users' preference1 will also become 5—definitely not what you want! Using copy() ensures each user gets their own independent preference set.

Flexible Version (Adjust Preferences Easily)

If you ever need to change the number or names of preferences, you can make the function more dynamic by passing the preference keys as a parameter:

def create_user_preferences(user_list, preference_keys=['preference1', 'preference2', 'preference3', 'preference4']):
    # Generate the inner dict on the fly for each user
    return {user: {key: 0 for key in preference_keys} for user in user_list}

Now you can call it with custom preferences, like:

custom_preferences = ['email_notifs', 'push_notifs', 'sms_notifs']
preference_dict = create_user_preferences(['userA', 'userB'], custom_preferences)

内容的提问来源于stack exchange,提问作者Aniket Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:01:25