Access data in a tuple

2

I have the following code:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate("2.json")
firebase_admin.initialize_app(cred,{
    'databaseURL':'https://new1-3b819.firebaseio.com/'
})

ref = db.reference('/Producto')
r1 = ref.get()
for key in r1.values(): #items() or values()
    for key in key.items():
        print(key)

Which gives me the following result:

('Cantidad', 10)
('Precio', 55)
('id', 9878)
('nombre', 'usb')
('ubicación', 'exe2')
('Cantidad', 2)
('Nombre', 'usb-blue')
('id', 98989)
('precio', 34)
('ubicación', 'exe2')
[Finished in 4.3s]

But what I need is that you only show me, for example, the fields that have only the key 'id'

This is what I hope to get:

  

id - 9878

     

id - 98989

Instead of the entire list I get.

    
asked by Revsky01 12.07.2018 в 18:46
source

1 answer

2

Instead of using items() you can simply use a get() to get the value for the key you need, which in this case is id :

for key in r1.values():
    id = key.get('id')
    print('id - %s' % id)

It should result in:

id - 9878 
id - 98989

In fact, if r1.values() returns a list of dictionaries, you can use a list by understanding to get all the IDs:

ids = [d.get('id') for d in r1.values()]
for id in ids:
    print('id - %s' % id)

Where the result of ids is a list:

[9878, 98989]
    
answered by 12.07.2018 / 18:57
source