【问题标题】:Can't get dictionary value from key in unicode dictionary无法从 unicode 字典中的键获取字典值
【发布时间】:2014-06-25 02:26:32
【问题描述】:

以下代码在变量webproperties_list中存储了一个unicode字典:

webproperties_list = service.management().webproperties().list(
        accountId='~all').execute()
profile_id = webproperties_list.get(u'defaultProfileId')
print profile_id

出于某种原因,u'defaultProfileId' 的键上的.get() 给了我None,即使我知道它在响应中。我还尝试了不带u 的get,但我仍然得到None 响应:

profile_id = webproperties_list.get('defaultProfileId')

在从键中获取值之前,我是否需要对 dict 做一些事情,还是我完全做错了什么?

更新:

这是我得到的回复:

{u'username': u'removed', u'kind': u'analytics#webproperties', u'items': [{u'profileCount': 1, u'kind': u'analytics#webproperty', u'name': u'removed', u'level': u'STANDARD', u'defaultProfileId': u'removed'.....

我需要检索u'defaultProfileId'的值

不太确定如何从字典中的列表中的字典中的键中获取值...

【问题讨论】:

  • 您是否尝试打印密钥、每个密钥的类型以及每个密钥的编码?
  • print(webproperties_list) 显示什么?
  • @wwii <type 'unicode'> <type 'unicode'> <type 'unicode'> <type 'unicode'> <type 'unicode'> <type 'unicode'> for for x in webproperties_list.keys(): print type(x)
  • @MrAlias 嗯,所以我只是意识到我需要的数据在一个字典中,该字典在整个响应字典中的列表中
  • 每个密钥的编码是否与您的密钥的编码匹配,例如它们都是“utf-8”还是“latin-q”n.a.

标签: python dictionary unicode


【解决方案1】:

要弄清楚如何访问它,有时一步一步来会有所帮助:

>>> d
{u'username': u'removed', u'items': [{u'profileCount': 1, u'defaultProfileId': u'removed', u'kind': u'analytics#webproperty', u'name': u'removed', u'level': u'STANDARD'}], u'kind': u'analytics#webproperties'}
>>> d['items']
[{u'profileCount': 1, u'defaultProfileId': u'removed', u'kind': u'analytics#webproperty', u'name': u'removed', u'level': u'STANDARD'}]
>>> d['items'][0]
{u'profileCount': 1, u'defaultProfileId': u'removed', u'kind': u'analytics#webproperty', u'name': u'removed', u'level': u'STANDARD'}
>>> d['items'][0]['defaultProfileId']
u'removed'

【讨论】:

  • 啊,我明白了。我想我最初应该把它打印得很漂亮。我错过了一些东西......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
相关资源
最近更新 更多