Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need help with these one-line procedures in python. 1. dict2list[dct,keylist) in

ID: 3665813 • Letter: N

Question

Need help with these one-line procedures in python.

1. dict2list[dct,keylist)

input: dictionary dct, list keylist consisting of the keys of dct

output: list L where L[i] = dct[keylist[i]] for i = 0,1,2,....len(keylist) -1

example: input dct = {'a' : 'A', 'b': 'B', 'c' : 'C'} and keylist = ['b','c','a'],

output: ['B' , 'C', 'A']

2. list2dict(L, keylist)

input: list L, list keylist of imutable items

output: dictionary that maps keylist[i] and L[i] = 0,1,2,....len(L) - 1

example: input L = ['A', 'B', 'C'] and keylist = ['a', 'b', 'c' ]

output: {'a': 'A', 'b' : 'B', 'c': 'C'}

using a comprehnsion that iterates over a zip or a range

Explanation / Answer

"for loop" will do the magic here. Observe the both one line statements.

-> To get list, I used [] and then defined elements followed by for loop

-> To get dictionary, I used {} and then for loop

1.

>>> dct = {'a' : 'A', 'b': 'B', 'c' : 'C'}
>>> keylist = ['b','c','a']
>>> [dct[keylist[i]] for i in range(0,len(keylist))]
['B', 'C', 'A']
>>>

2.

>>> ================================ RESTART ================================
>>> L = ['A', 'B', 'C']
>>> keylist = ['a', 'b', 'c' ]
>>> {keylist[i]:L[i] for i in range(0,len(keylist))}
{'a': 'A', 'c': 'C', 'b': 'B'}
>>>

I have given one liner statements. If you want them to be in function, then just define functions with def syntax and just return this one line. It will do the magic.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote