我如何通过转换为列表的json进行排序?

时间:2017-04-04 12:43:29

标签: python json list python-3.x

假设我有一个像这样的对象:

[
  {
    "id": 2,
    "name": "cat"
  },
  {
    "id": 6,
    "name": "dog"
  },
  {
    "id": 8,
    "name": "horse"
  },
  {
    "id": 10,
    "name": "turtle"
  }
]

我希望编写一个可以获取输入ID并告诉我相关名称的函数。 如果为animal_list分配了该列表,我如何找到与6相关的动物? animal_list [ID == 6]

4 个答案:

答案 0 :(得分:0)

最好是你可以将列表转换为字典,就像@ShadowRanger所说的那样,但如果你不能将列表推导与if语句一起使用:

my_list = [
  {
    "id": 2,
    "name": "cat"
  },
  {
    "id": 6,
    "name": "dog"
  },
  {
    "id": 8,
    "name": "horse"
  },
  {
    "id": 10,
    "name": "turtle"
  }
]

def get_by_id(the_list, id):
    found = [dict for dict in the_list if dict['id'] == id]
    if found:
        return found[0]
    return None 

print(get_by_id(my_list, 6))

# will output: {'id': 6, 'name': 'dog'}

答案 1 :(得分:0)

animal_list是您在问题中提供的列表

animal_list = [
      {
       "id": 2,
       "name": "cat"
      },
      {
       "id": 6,
       "name": "dog"
      },
      {
       "id": 8,
       "name": "horse"
      },
      {
       "id": 10,
       "name": "turtle"
      }
    ]
def get_animal(id):
    found = 0
    for i in animal_list:
        if animal_list[i]["id"] == id :
            found = 1
            print animal_list[i]["name"]
    if found == 0:
            print "animal not found"

答案 2 :(得分:0)

您可以将数据导入为JSON,并使用dict结构进行处理。

我创建了一个函数,如果有一个有效的密钥将返回动物名称,如果没有密钥,则返回none。

<强>代码:

s = '[{"id": 2,"name": "cat"},{"id": 6,"name": "dog"},{"id": 8,"name": "horse"},{"id": 10,"name": "turtle"}]'

def search_animal(s, num):
    import json    
    data = json.loads(s)
    for d in data:
        if d['id'] == num:
            print(d['name'])

search_animal(s, 2)
search_animal(s, 6)

<强>输出:

cat
dog

答案 3 :(得分:0)

list = [
  {
    "id": 2,
    "name": "cat"
  },
  {
    "id": 6,
    "name": "dog"
  },
  {
    "id": 8,
    "name": "horse"
  },
  {
    "id": 10,
    "name": "turtle"
  }
]


id = input("Enter ID..! ")

for data in list:
    if data.get('id') == id:
        print data.get('name')