使用生成器表达式打印每个json对象的多个键

时间:2018-10-14 00:57:40

标签: python json

我正在使用此API https://jsonplaceholder.typicode.com/posts列出所有类似的帖子,

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },

我的代码,

session  = requests.Session()
payload = session.request("GET", "https://jsonplaceholder.typicode.com/posts", timeout = 30).json()

print(payload)

现在我想按id对所有对象进行排序,

d = sorted(payload, key=operator.itemgetter("id"))
print(d)

现在,如果我想按标题长度排序,

我不知道如何使用operator来提供len(title)作为密钥吗?

使用带有for循环的生成器表达式而不是key

d = sorted(len(value["title"]) for value in payload)
print(d)

输出

[12, 12, 14, 14, 15, 18, 20, 20, 20, 20, 23, 24, 24, 24, 24, 24, 24, 25, 25, 26, 26, 26, 27, 27, 29, 29, 29, 30, 30, 30, 31, 32, 32, 32, 32, 33, 33, 33, 33, 34, 34, 34, 35, 36, 37, 37, 37, 37, 38, 38, 39, 39, 39, 40, 40, 41, 41, 41, 41, 42, 42, 42, 42, 43, 43, 43, 43, 44, 44, 44, 45, 46, 47, 47, 47, 49, 50, 50, 51, 51, 53, 53, 53, 53, 54, 55, 55, 55, 57, 59, 60, 60, 67, 68, 72, 74, 76, 76, 78, 79]

如您所见,这给了我每个title的长度,但是我不知道实际的标题。我还如何为每个json对象在其长度旁边打印title

2 个答案:

答案 0 :(得分:1)

使用lambda指定自定义排序标准:

d = sorted(payload, key=lambda x: len(x['title']))
print(d)

官方文档中实际上有一个使用lambda进行排序的示例:https://docs.python.org/3/howto/sorting.html#key-functions

然后,要打印标题及其长度,您可以执行以下操作:

titles = [(p['title'], len(p['title'])) for p in sorted(payload, key=lambda x: len(x['title']))]
print(titles)
>>> [('qui est esse', 12), ('sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 74)]

答案 1 :(得分:1)

一个人可以分三个阶段做到这一点:

1)提取标题

2)按len排序

3)构建对

这仍然很适合一行,并且实际上很可读:

[(x, len(x)) for x in sorted((x['title'] for x in mock), key=len)]

样品运行

[('jfzq', 4), ('uqixc', 5), ('xparg', 5), ('uvuuk', 5), ('gsibnde', 7), ('pophwash', 8), ('cudisvgf', 8), ('swptewjg', 8), ('rthjtjylh', 9), ('ezvwpqhfn', 9)]

用于创建mock数据的代码:

>>> from random import choices, randint
>>> from string import ascii_lowercase
>>> 
>>> mock = [{k: ''.join(choices(ascii_lowercase, k=randint(4, 10))) for k in ('userId', 'id', 'title', 'body')} for _ in range(10)]