I have a list of strings (both strings and list can be large). I want to build dictionary out of only certain elements from the list.
l = ['aaa 0','bbb 1','ccc 2','ddd 3','abc 1']
wanted = set(['aaa','abc'])
dict([x.split() for x in l if x.split()[0] in wanted])
{'aaa': '0', 'abc': '1'}
Can this be done without calling split()
operation twice?
Using nested generator expression ((x.split() for x in l)
) to yield key, value pairs:
>>> l = ['aaa 0', 'bbb 1', 'ccc 2', 'ddd 3', 'abc 1']
>>> wanted = {'aaa', 'abc'}
>>> {key: value for key, value in (x.split() for x in l) if key in wanted}
{'abc': '1', 'aaa': '0'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With