Skip to content Skip to sidebar Skip to footer

Why Do We Need To Convert A Zipped Object Into A List

I am trying to complete a datacamp exercise in which I am required to convert 2 lists into a zip object and then into a dict to finally get a dataframe using pandas. However, If I

Solution 1:

I think dict(zipped) convert zip object or list object to dictionary. So here convert to list is redundant.


But if want create DataFrame from zip object in python 3 it is problem, need convert to lists of tuples first:

a = ['United States', 'Soviet Union', 'United Kingdom']
b = [1118, 473, 273]
c = ['Country', 'Total']

zipped = zip(a,b)
print(zipped)
<zip object at 0x000000000DC4E8C8>

df = pd.DataFrame(zipped, columns=c)
print(df)
TypeError: data argument can't be an iterator

print(list(zipped))
[('United States', 1118), ('Soviet Union', 473), ('United Kingdom', 273)]

df = pd.DataFrame(list(zipped), columns=c)
print(df)

          Country  Total
0   United States   1118
1    Soviet Union    473
2  United Kingdom    273

Post a Comment for "Why Do We Need To Convert A Zipped Object Into A List"