blizzy
blizzy

Reputation: 55

Python Dictionary: Iterating values in a list

I want to iterate values inside a list but I get this kind of output which is I don't like:

First I have a dictionary, and I converted it into lists.

listb=[{'id': '1b33b33f-8e92-4068-a459-0a1de0febb7c'}, {'id': 'c56502b9-0632-4f9f-88b9-70f40e61ef5d'}]

Code for converting dictionary values into a list:

vol = [i["id"] for i in listb]

and I wanted to iterate the values inside a lists:

for i in vol:
    print(i[0])

But I get these values:

1
c

The desired output would be:

1b33b33f-8e92-4068-a459-0a1de0febb7c
c56502b9-0632-4f9f-88b9-70f40e61ef5d

Upvotes: 1

Views: 51

Answers (2)

Eduardo Morales
Eduardo Morales

Reputation: 823

i is the complete id.

i[0] is the 0th index, or the first character in the string i.

In this case,

1b33b33f-8e92-4068-a459-0a1de0febb7c[0] = 1
c56502b9-0632-4f9f-88b9-70f40e61ef5d[0] = c

Simply print the entire element, rather than just the index.

Change your code to:

for i in vol:
    print(i)

I would even suggest you rename your variable i to id.

for id in vol:
    print(id)

Upvotes: 1

Shubham Vasaikar
Shubham Vasaikar

Reputation: 728

You just need to change your print statement to like this:

for i in vol:
    print(i)

Explanation:

When you run this:

vol = [i["id"] for i in listb]

The contents in vol look like this:

>>> vol
['1b33b33f-8e92-4068-a459-0a1de0febb7c', 'c56502b9-0632-4f9f-88b9-70f40e61ef5d']

So you just need to print every element in the list vol. When you write i[0] what happens is that you are accessing the first element of the string in i.

Upvotes: 3

Related Questions