【问题标题】:parse data from Dictionary in python在python中解析字典中的数据
【发布时间】:2017-07-07 05:09:59
【问题描述】:

所以我有这本字典“运行”:

[{
'id': 12,
'suite_id': 2,
'name': 'name',
'description': "desc.",
'nice_id': 3,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 1,
'blocked_count': 2,
'untested_count': 3,
'retest_count': 4,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'projekti_id': 1,
'plan_id': None,
'created_on': 12343214,
'created_by': 11,
'url': 'google.com'
}, {
'id': 16,
'suite_id': 2,
'name': 'namae)',
'description': "desc1",
'nice_id': 5,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 100,
'blocked_count': 1,
'untested_count': 3,
'retest_count': 2,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'prokti_id': 7,
'plan_id': None,
'created_on': 4321341644,
'created_by': 11,
'url': 'google.com/2' }

有大约 50 次“id”。这只是其中的一部分。 我需要找到所有“id”:s(不是 joku_ids、ncie_ids 等。只有“id”)并为它们制作一个字符串/字典 名称和描述相同

我试过了:

j = json.load(run)
ids = (j["id"])

j = json.load(run)
names = (j["name"])

j = json.load(run)
descriptions = (j["description"])

但它会返回:

AttributeError: 'list' object has no attribute 'read'

我还需要发送一个带有特定 id 的请求,在这种情况下,特定 id 用 o 标记。所以我[o] 请求代码如下:

test = client.send_get('get_tests/1/ ')

所以我需要 id[o] 而不是 1。 我试过了

test = client.send_get('get_tests/' + id[o] + '/ ')

但它会返回:

TypeError: 'int' object is not subscriptable

【问题讨论】:

  • 所以你想要id = [d['id'] for d in runs]
  • 你期望什么答案,你想要结果是列表还是字典?

标签: python json string parsing dictionary


【解决方案1】:

也许这对你有帮助。

id = []
for i in runs :
    id.append(i.get('id'))

[12, 16]

【讨论】:

  • 这是我的荣幸。
【解决方案2】:

您正在尝试将列表传递给json.load 函数。请阅读docs。 Load() 不接受列表,它接受

一个支持 .read() 的类文件对象,其中包含一个 JSON 文档

【讨论】:

    【解决方案3】:

    如果您希望您的结果出现在字典列表中,那么:

    result = [{x:y} for i in range(len(data)) for x,y in data[i].items() if x=='id' or x=='name' or x=='description']
    

    输出:

    [{'name': 'name'}, {'id': 12}, {'description': 'desc.'}, {'name': 'namae)'}, {'id': 16}, {'description': 'desc1'}]
    

    data 是您的字典数据列表。 希望这个答案对您有所帮助。

    【讨论】:

    • 这也有效,但与.光辉的回答。谢谢
    • 对不起。忘记 :)。我的代码非常接近完成,但是我的字符串获取信息有问题。它应该像 ('get_tests/1/ ') 并且我需要一个 id[o] 而不是 1。我尝试过 ('get_tests/' + id[o] + '/') 但它没有工作
    • 我没有得到您想要的完整内容,请正确提及或更改您的问题。
    猜你喜欢
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2014-03-30
    相关资源
    最近更新 更多