为什么这个条件字典理解不起作用



当我运行这个时,当我期望一个包含profile_fields中列出的键的新dict时,它返回{}。我做错了什么?

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_fields只包含一个字符串字面值

您可以定义profile_fields列表

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

可以使用PEP 8

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

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

您的profile_list实际上应该是这样的:

profile_fields = [
    'location',
    'email_address',
    'full_name',
    'github',
    'image',
    'public_key',
    'twitter',
    'user_id',
    'user_name',
    'website'
]
如前所述,逗号应该在组成字符串的引号之外的。目前,您有一个包含单个元素的列表,它永远不会匹配user字典中的任何键。

最新更新