Python 为什么这种有条件的听写理解不起作用?

Python 为什么这种有条件的听写理解不起作用?,python,python-3.x,Python,Python 3.x,当我运行此命令时,它返回{},而我期望新的dict包含profile_字段中列出的键。我做错了什么 import datetime user = {'email_optin': False, 'paid': 0, 'location': None, 'account_state': 'enabled', 'ip_address': '1.1.1.1', 'modified_timestamp': 1440107582, 'image': None, 'created': datetime.da

当我运行此命令时,它返回
{}
,而我期望新的
dict
包含profile_字段中列出的键。我做错了什么

import datetime

user = {'email_optin': False, 'paid': 0, 'location': None, 'account_state': 'enabled', 'ip_address': '1.1.1.1', 'modified_timestamp': 1440107582, 'image': None, 'created': datetime.datetime(2015, 8, 20, 21, 53, 2, 436540), 'website': None, 'public_key': None, 'last_seen': datetime.datetime(2015, 8, 20, 21, 53, 2, 434959), 'full_name': None, 'user_id': 'jk4vv6cucgxtq6s4i3rgmdcwltvva2fl', 'confirmed': False, 'twitter': None, 'email_address': 'h@example.org', 'modified': datetime.datetime(2015, 8, 20, 21, 53, 2, 436554), 'password': '$5$rounds=110000$HnkKE5jWtb1I1cps$dOu0PeijD.enkVd85ofpVpI.1p9wpAsx8fLLSENEuQ1', 'github': None, 'created_timestamp': 1440107582, 'subscription_plan': '', 'user_name': 'xdc'}



profile_fields = [
'location,'
'email_address,'
'full_name,'
'github,'
'image,'
'public_key,'
'twitter,'
'user_id,'
'user_name,'
'website'
]

profile = {k:v for k,v in user.items() if k in profile_fields }
print('profile')
print(profile)

编辑:上面的问题是一条消息,我的16小时编码日已经结束。

因为你把逗号放在引号里而不是外面。您的列表
profile\u字段
只包含一个字符串文字。

您的列表有问题。应该是这样的,

profile_fields = ['location','email_address','full_name','github','image','public_key','twitter','user_id','user_name','website']

您的
profile\u列表实际上应该如下所示:

profile_fields = [
    'location',
    'email_address',
    'full_name',
    'github',
    'image',
    'public_key',
    'twitter',
    'user_id',
    'user_name',
    'website'
]

如前所述,逗号应该位于构成字符串的引号之外。您当前有一个包含单个元素的列表,该元素永远不会与
用户
词典中的任何键匹配。这是一个简单的解决方案。

您可以像列表一样定义配置文件字段

profile_fields = [
        'location', 'email_address', 'full_name',
        'github', 'image', 'public_key', 'twitter',
        'user_id', 'user_name','website'
            ]

你可以使用

@OP-the
超出了
的“字符串”
看到了吗?我想我现在需要睡觉了。