python/using_zip.py

24 lines
612 B
Python

#Zipping two lists of equal length
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
paired = list(zip(names, scores))
print(paired)
#Creating a dictionary
keys = ['id', 'name', 'age']
values = [101, 'Alice', 30]
data = dict(zip(keys, values))
print(data)
#Unzipping the zipped lists
zipped = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
names, scores = zip(*zipped)
print(names) # ('Alice', 'Bob', 'Charlie')
print(scores) # (85, 92, 78)
#Unzipping the dictionary to a list of key, value tuples
data = {'id': 101, 'name': "Alice", 'age' : 30}
keys, values = zip(*data.items())
print(keys, values)