Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing values in list inside dictionary when you don't know the count

Tags:

python

I have output in below form:

data = {ItemA: [123456, 123654], ItemB: [456789, 456987]}

To get the values, I can access them as data.ItemA[0], data.ItemA[1]

But how do you deal when you don't know how many values are there for ItemA in the list. How can I get all individual values of ItemA without knowing how many items will be in list beforehand.

like image 933
pylearn Avatar asked Dec 20 '25 03:12

pylearn


2 Answers

You can just access the entire list and use it however you want:

data = {'ItemA': [123456, 123654], 'ItemB': [456789, 456987]}
my_list = data['ItemA']

my_list will then just be the entire list, and you can check its length, pull out specific items (like you were doing before), iterate through it etc.

like image 167
Simon Avatar answered Dec 22 '25 17:12

Simon


So for that you need to iterate over dictionary and than from the key you get you need to iterate the list inside that.

data = {'ItemA': [123456, 123654], 'ItemB': [456789, 456987]}
for key in data:
    for items in data[key]:
        print(key ,':' , items)

Key will iterate over dictionary and contains 'ItemA' and 'ItemB'. Then from there yoū can iterate over that dictionary key and get list

like image 26
Akhil Pathania Avatar answered Dec 22 '25 19:12

Akhil Pathania



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!