I have this python loop:
for idx, device in enumerate(account.covers.values()):
so then when i do print(device.device_id)
I get this result:
chdibcb32
chdbvvo13
f82074242
because there is 3 devices, which is right. Now i want to access the first one only chdibcb32
. I tried print(device.device_id[0])
, but that just prints the first letter of each output.
how can i do this?
CodePudding user response:
Why bother looping?
If account.covers.values()
returns a sequence, you can use indexing to get its first element:
device = account.covers.values()[0]
print(device.device_id)
If it's an iterator, you can use next()
:
device = next(account.covers.values())
If it's some other iterable (like a dict view or set), you can use next(iter())
:
device = next(iter(account.covers.values()))
- Sidenote: this solution is basically equivalent to:
for device in account.covers.values(): break
CodePudding user response:
You don't have to loop. You can do it like this print(account.covers.values()[0].device_id)
if I'm not mistaken.
CodePudding user response:
it is because you use for each loop. Each item is using string but not list. Thats why python chose the first letter instead of the item in the list