Home > Blockchain >  Converting a list to dictionary having key value pairs
Converting a list to dictionary having key value pairs

Time:09-28

I have a list and i would like to convert it into a dictionary such that key:value pairs should be like

{'apple':87, 'fan':88 ,'jackal':89,...}

Following is the list :

values_list = ['apple', 87, 'fan', 88, 'jackal', 89, 'bat', 98, 'car', 84, 'ice', 80, 'car', 86, 'apple', 82, 'goat', 80, 'dog', 81, 'cat', 80, 'eagle', 90, 'eagle', 98, 'hawk', 89, 'dog', 79, 'fan', 89, 'goat', 85, 'car', 81, 'hawk', 90, 'ice', 85, 'cat', 78, 'goat', 84, 'jackal', 90, 'apple', 80, 'ice', 87, 'bat', 94, 'bat', 92, 'jackal', 91, 'eagle', 93, 'fan', 85]

following is the python script written to do the task :

for i in range(0,length(values_list),2):
    value_count_dict = {values_list[i] : values_list[i 1]}
    print(value_count_dict)
    values_count_dict = dict(value_count_dict)

print(values_count_dict)

output of the script :

output of the script

But expecting a single dictionary with all key:value pairs in it. Thank you in advance!

CodePudding user response:

You've misspelled len as length.

The most Pythonic way of doing this is likely with a dictionary comprehension and range using the step argument.

{values_list[i]: values_list[i 1] for i in range(0, len(values_list), 2)}
# {'apple': 80, 'fan': 85, 'jackal': 91, 'bat': 92, 'car': 81, 'ice': 87, 'goat': 84, 'dog': 79, 'cat': 78, 'eagle': 93, 'hawk': 90}

In your code you also assign a new dictionary to value_count_dict on each iteration. You want to assign a value to a new key in the dictionary on each iteration.

value_count_dict = {}
for i in range(0, len(values_list), 2):
    value_count_dict[values_list[i]] = values_list[i 1]

CodePudding user response:

just use a dictionary comprehension

adict = {values_list[i]:values_list[i 1] for i in range(0,length(values_list),2)}

to not change your code so much you could do

values_count_dict = {}
for i in range(0,length(values_list),2):
    values_count_dict[values_list[i]] = values_list[i 1]
    print(value_count_dict)
  • Related