I am working with dictionaries in python.
s = {'k1':['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']}
I have created code as :
d = {}
for values in enumerate(s.values()[0]):
if values[0]<2:
d[values[1]] = 'True'
else:
d[values[1]] = 'False'
Can I convert this into one liner code using list comprehension or lambda?
I need answer as :
{'aa': 'True', 'bb': 'True', 'cc': 'False', 'dd': 'False', 'ee': 'False', 'ff': 'False', 'gg': 'False'}
updated – sry code typing mistake
In response to:
the one liner is:
What you are doing is nonsensical. Essentially the code you posted will always set
d['ans']to'True'whens.values()[0]has a length less than2(else'False'). This is because the first element in the 2-tuple yielded byenumerateis the index (which you are comparing with<2). For all cases where the length of list is greater than 2, theelseclause will keep setting it to'False'. You dont even need a loop for this.Update:
For your new version:
or
update 2: or if you want to update an existing dictionary: