1

So I have this dict i take from some page using request. Now i use its values to create list. How can I iterate on that list to extract and use each item? I have already tried something like this:

  for component in values:
        if values.index(component) > 0:
            value = values.pop()

but its give me only some items and leave others.

Remerio
  • 11
  • 3
  • well you have a condition that the index is >0, so of course your code will filter all those elements with index <=0. You should provide an example of a dictionary, how you convert it to a list, what result does your code return and what is the expected result. Then with all this data we can take a look at why the result differ from the expected –  Oct 05 '22 at 10:23
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – buran Oct 05 '22 at 10:53

2 Answers2

1

It looks like you only need to iterate over the list, not remove any elements. If you want to create a list from an existing one, you can use the list comprehension:

same_values = [x for x in values]

And if you want, you can add a specific condition:

positive_values = [x for x in values if x > 0]
Florin C.
  • 593
  • 4
  • 13
0

Given, you got a dictionary and need the values in the form of a list. Let dct be your dictionary, then extract the values from the dictionary...

list_values = list( dct.values() )

If you want to filter the values based on the index of the dictionary, then you can use the below code to filter the values based on the index from the dictionary.

for i, j in zip( dct.keys(), dct.values() ):
    if i > 0:
        print(j)

The functions keys() and values() returns the indexes and values at that index separately, which are joined using the zip function and stored into i and j respectively at each iteration of the for-loop.

  • There is no need to zip the keys with the values, _items()_ does that very efficient: `for i, j in dct.items():` And the if condition inside a for loop is not very pythonic. It screams to be a filter or a list comprehension. – Florin C. Oct 10 '22 at 13:40