In: Computer Science
Python programming question:
Suppose i have a list like:
['a:10', 'b:9', 'c:8', 'd:7', 'e:6', 'f:5', 'g:4', 'h:3', 'i:2', 'j:1', 'k:0']
How do i trans form this into a dictionary or something i can plot a graph with using these keys and value pairs?
thanks.
If you have any queries please comment in the comments section I will surely help you out and if you found this solution to be helpful kindly upvote.
Solution :
Code:
import matplotlib.pyplot as plt
# transform function to transform list into a dictionary
def transform(li):
# declare an empty list
di={}
# iterate over the list
for item in li:
# split the item on the basis of :
items=item.split(':')
# make a key-value pair in the dictionary
di[items[0]]=items[1]
# return the dictionary
return di
# function to plot a bar graph
def plot(di):
# plot a bar graph using keys and values of the dictionary
plt.bar(di.keys(),di.values())
# declare the list
li = ['a:10', 'b:9', 'c:8', 'd:7', 'e:6', 'f:5', 'g:4', 'h:3',
'i:2', 'j:1', 'k:0']
# call the transform function to transform the list to a
dictionary
di=transform(li)
# print the dictionary
print(di)
# call the plot function to plot the values
plot(di)
Output :