Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert several lists to a list of dicts in python?

Tags:

python

I have a program that takes 2 numbers and subtracts them and also tells us if the individual places i.e. ones, tens and hundreds are smaller than the number they are being subtracted from and if they need to borrow.

a=2345
b=1266
o=[int(d) for d in str(a)]
a=[int(d) for d in str(a)]
b=[int(d) for d in str(b)]
x=len(a)
y=len(b)
i=1
state=[]
c=[]
for n in range(x):
    if a[x-i]<b[y-i]:
        a[x-i]+=10
        a[x-i-1]-=1
        state.append(True)
    else:
        state.append(False)
    i+=1
i=1    
for m in range(x):
    c.append(a[x-i]-b[y-i])
    i+=1
c=c[::-1]
print(o) #before borrow
print(a) #after borrow
print(b) #number to subtract
print(c) #result
print(state) #if borrowed

And this is my output:

[2, 3, 4, 5]
[2, 2, 13, 15]
[1, 2, 6, 6]
[1, 0, 7, 9]
[False, False, False, False]

Here is my question: 1) I want to map the results to a list of dictionary for each place like below:

[{'initial_num': '5', 'after_borrow': '15', 'state': True, 'after_subtract': '9'},
{'initial_num': '4', 'after_borrow': '13', 'state': True, 'after_subtract': '7'}...]

How do I do this so that I have 4 dicts in the list each corresponding to a particular position?

like image 817
adfgasda Avatar asked Feb 25 '20 08:02

adfgasda


People also ask

Are Dicts faster than lists Python?

Analysis Of The Test Run ResultA dictionary is 6.6 times faster than a list when we lookup in 100 items.

Can you create a dictionary of lists in Python?

In Python dictionary, it is an unordered and immutable data type and can be used as a keys element. To create a dictionary of lists, first, we insert key-value within the curly brackets and to obtain the values of a dictionary, and then use the key name within the square brackets.

How do I put all the values in a dictionary into a list?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.

Can you convert a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


1 Answers

You can zip the lists you are interested in to dicts with list comprehension

l = [{'initial_num': x, 'after_borrow': y, 'state': z, 'after_subtract': k} for x, y, z, k in zip(o, a, state, c)]
like image 111
Guy Avatar answered Oct 24 '22 04:10

Guy