A
A
axtrace2016-10-02 07:51:32
Python
axtrace, 2016-10-02 07:51:32

Python json Find by value, how?

{'cars': [{'model': 'Mitsubishi Lancer', 'id': 5419, 'plate': 'T111TT199'}, {'model': 'Honda VFR750', 'id': 5420, 'plate': 'E222EE177'}]}

How can I get the corresponding model from json, knowing the value of plate?
For example, input 'E222EE177', output 'Honda VFR750'

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Юрий, 2016-10-02
@axtrace

import json

def model_by_plate(js, plate):
    for car in json.loads(js)['cars']:
        if car['plate'] == plate:
            return car['model']

print(model_by_plate(data, 'E222EE177'))

Владимир Куц, 2016-10-02
@fox_12 Куратор тега Python

>>> str1={'cars': [{'model': 'Mitsubishi Lancer', 'id': 5419, 'plate': 'T111TT199'}, {'model': 'Honda VFR750', 'id': 5420, 'plate': 'E222EE177'}]}
>>> filter(lambda x: x['plate']=='E222EE177', str1['cars'])[0]['model']
'Honda VFR750'

D
Dimonchik, 2016-10-02
@dimonchik2013

ответы шикарны ))
см. еще json.loads() для первого шага

T
tplus, 2016-10-02
@tplus

def main():
  cars = {'cars': [{'model': 'Mitsubishi Lancer', 'id': 5419, 'plate': 'T111TT199'}, {'model': 'Honda VFR750', 'id': 5420, 'plate': 'E222EE177'}]}
  for smth in cars['cars']:
    if smth['plate'] == 'E222EE177':
      print smth['model']
      break

>> Honda VFR750

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question