A
A
Alex F2021-08-25 08:09:47
Python
Alex F, 2021-08-25 08:09:47

How to find a key by value?

There is a dictionary

{"devices": [{"id": 2916,
      "name": "Ard2560",
      "my": 0,
      "owner": "17293",
      "mac": "",
      "cmd": 1,
      "location": "Инской, ул.Сергея Тюленина, 41",
      "distance": 30.02,
      "time": 1629865863,
      "lat": 54.4222,
      "lng": 86.4295,
      "liked": 0,
      "uptime": 0,
      "sensors": [
        {"id": 20650,
          "mac": "",
          "fav": 0,
          "pub": 2,
          "type": 1,
          "name": "Температура",
          "value": 25.29,
          "unit": "°",
          "time": 1629865863,
          "changed": 1629865863,
          "trend": 0},
        {"id": 20668,
          "mac": "",
          "fav": 0,
          "pub": 1,
          "type": 3,
          "name": "Давление",
          "value": 746.73,
          "unit": "mmHg",
          "time": 1629865863,
          "changed": 1629865863,
          "trend": 0},
        {
          "id": 20994,
          "mac": "",
          "fav": 0,
          "pub": 1,
          "type": 2,
          "name": "Влажность",
          "value": 52.09,
          "unit": "%",
          "time": 1629865863,
          "changed": 1629865863,
          "trend": 0
}]}]}


How to get the number(in this case [1]) of "id" based on its value "mmHg"?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex F, 2021-08-25
@delvin-fil

Thank you all, Sergey Gornostaev , MinTnt , MinTnt ! Got me thinking!
Own Json

#!/usr/bin/env python3.9

import json
import re
from collections import Counter

with open('/home/delvin/codding/pogoda/sensorsNearby.json') as json_facta:
    fact = json.load(json_facta)
    json_facta.close()
array = fact['devices']
numkeys = Counter(i for val in array for i in val)['id']
startnum = 0
sensor = 0
unit = ''
pressure = 0

while startnum <= numkeys:
    for device in fact['devices']:
        if device['location'] == "Ленинск-Кузнецкий, Городская ул., 10":
            pressure = device['id']
            temperature = device['sensors'][-1]['value']
            temperature = round(temperature)
            unit = device['sensors'][-1]['unit']
    startnum += 1

print (f"{temperature}{unit}")

Exhaust:
27°

S
Sergey Gornostaev, 2021-08-25
@sergey-gornostaev

Bust.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question