-1

I have a list of dictionary which looks like.

[
  {
    "deviceId": "d61e",
    "floor": "L1",
    "id": "l1-topic"
  },
  {
    "deviceId": "fd00::212:4b00:1957:d197",
    "floor": "L3",
    "id": "l3-topic"
  },
  {
    "deviceId": "fd00::212:4b00:1957:d1a3",
    "floor": "L2",
    "id": "l2-topic"
  }
]

Can somone help me with how do I extract the deviceId of a given floor like L2?

I have tried converting it into a pandas dataframe and trying to extract using some operations, is it possible to do it in a more pythonic way.

Thanks.

chink
  • 1,505
  • 3
  • 28
  • 70
  • 1
    Does this answer your question? [Python list of dictionaries search](https://stackoverflow.com/questions/8653516/python-list-of-dictionaries-search) – Georgy Jan 30 '20 at 10:28

3 Answers3

1

You can iterate and get the deviceId when floor is equal to L2.

>>> res = next((d['deviceId'] for d in l if d['floor']=='L2'), None)
>>> res
'fd00::212:4b00:1957:d1a3'
abc
  • 11,579
  • 2
  • 26
  • 51
  • I understand that `l` is the is my list. What does next do in this case? – chink Jan 28 '20 at 15:07
  • l is your list. res will get the next item from the iterator, and in case no dictionary has a floor L2 then res gets None. – abc Jan 28 '20 at 16:44
1

If i understand the question right, you want to extract deviceId's that are on floor. You can use this:

result = []
for key,data in devices.items():
    if data.floor=="L2":
       result.append(data.deviceId)

Now the result contain, all ids in floor

But you should really consider storing deviceId's for floors in different way.

I hope this helped you

1

Same logic as the one from @Jiri Otuupal, but in a more compact form using list comprehension:

# I assume the given list is stored in a variable called "dicts"
res = [d['deviceId'] for d in dicts if d['floor'] == 'L2']

OUTPUT

print(res)
# ['fd00::212:4b00:1957:d1a3'] 

To the best of my knowledge, when working with lists in combinations with loops and conditions, list comprehensions are the most pythonic way of getting the desired result. Most of the times they are faster, shorter in code and easier to read than any other solutions.

AnsFourtyTwo
  • 2,480
  • 2
  • 13
  • 33