xxxxxxxxxx
my_list = ['Nagendra','Babu','Nitesh','Sathya']
my_dict = dict()
for index,value in enumerate(my_list):
my_dict[index] = value
print(my_dict)
#OUTPUT
{0: 'Nagendra', 1: 'Babu', 2: 'Nitesh', 3: 'Sathya'}
xxxxxxxxxx
# This is our example dictionary
petAges = {"Cat": 4, "Dog": 2, "Fish": 1, "Parrot": 5}
# This will be our list, epmty for now
petAgesList = []
# Search through the dictionary and find all the keys and values
for key, value in petAges.items():
petAgesList.append([key, value]) # Add the key and value to the list
print(petAgesList) # Print the now-filled list
# Output: [['Cat', 4], ['Dog', 2], ['Fish', 1], ['Parrot', 5]]
xxxxxxxxxx
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
xxxxxxxxxx
#This is to convert two lists into a dictionary in Python
#given ListA is key
#given ListB is value
listA = ['itemA','itemB']
listB = ['priceA','priceB']
dict(zip(listA, listB))
# Returns
{'itemA': 'priceA',
'itemB': 'priceB'
}
xxxxxxxxxx
>> d = {'a': 'Arthur', 'b': 'Belling'}
>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]
>> d.keys()
['a', 'b']
>> d.values()
['Arthur', 'Belling']
xxxxxxxxxx
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
out = dict(zip(keys, values))
xxxxxxxxxx
The zip() function is used to combine two or more iterables into a single iterable of tuples. Here is the syntax:
my_list1 = ["apple", "banana", "cherry"]
my_list2 = [1, 2, 3]
my_dict = dict(zip(my_list1, my_list2))
print(my_dict)
#Output
{'apple': 1, 'banana': 2, 'cherry': 3}
I hope it will help you. Thank you :)
For more refer link: https://www.programmingquest.com/2023/03/simplify-your-code-how-to-convert-lists.html
xxxxxxxxxx
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
out = dict(zip(keys, values))
xxxxxxxxxx
keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
out = dict(zip(keys, values))