解析嵌套字典

时间:2016-01-22 14:58:58

标签: python dictionary

我想为所有URL条目解析以下嵌套字典。它们应该写成list

{u'_id': ObjectId('56a22819ffd6f'),
 u'books': [{u'id': {u'id': u'4311'},
   u'link': {u'name': u'Operating Business',
    u'url': u'http://ffff'}},
  {u'id': {u'id': u'4310'},
   u'link': {u'name': u'Operating Business',
    u'url': u'http://zzzzz'}},
  {u'id': {u'id': u'7462'},
   u'link': {u'name': u'European Credit Trading',
    u'url': u'http://xxxx'}},
  {u'id': {u'id': u'3258'},
   u'link': {u'name': u'Operating Business',
    u'url': u'http://dddddd'}},
  {u'id': {u'id': u'7463'},
   u'link': {u'name': u'US Credit Trading',
    u'url': u'http://aaaaa'}}],
 u'created': datetime.datetime(2016, 1, 2, 13, 1, 12, 744000),
 u'id': u'lingering-smoke',
 u'valuationDate': datetime.datetime(170, 1, 1, 0, 0, 16, 821000)}

我该怎么做?

2 个答案:

答案 0 :(得分:2)

让dd = dict

dd = {full dictionary}
url_list = []
for ll in dd['books']:
    url_list.append(ll['link']['url'])

print url_list

[u'http://ffff', u'http://zzzzz', u'http://xxxx', u'http://dddddd', u'http://aaaaa']

答案 1 :(得分:1)

假设@gkusner使用相同的variables替代方法来解决它,例如

>>> dd = {full dictionary}
>>> [ll['link']['url'] for ll in ['books']]
[u'http://ffff', u'http://zzzzz', u'http://xxxx', u'http://dddddd', u'http://aaaaa']