Python: Append a list to an existing list assigned to a key in a dictionary? -
lets have dict key= 'keys'
>>> keys 'taste'
after few lines..output
>>> {'taste': ('sweet', 'sour', 'juicy', 'melon-like')}
this code snippet
from collections import defaultdict agent=defaultdict(str) key_list=[] key_list=[(keys,tuple(key_list))] agent=dict(key_list) #agent[keys]+=key_list
what want know is, there way lets have agent= {'taste': ('sweet', 'sour', 'juicy', 'melon-like')}
i want add list
key_list=['yuck!','tasty','smoothie']
and agent.setdefault('taste',[]).append(key_list)
and have output like:
{'taste': ('sweet', 'sour', 'juicy', 'melon-like','yuck!','tasty','smoothie')}
instead of
{'taste': ('sweet', 'sour', 'juicy', 'melon-like',['yuck!','tasty','smoothie'])}
is there way that?
inshort:
- i want add list existing list,which value key in dictionary (w/o iterations find particular key)
- check if element being fed in list contains element in list value particular key, 'taste' here (could string, here)
check out:
>>> tst = {'taste': ('sweet', 'sour', 'juicy', 'melon-like')} >>> tst.get('taste', ()) #default () if not exist. ('sweet', 'sour', 'juicy', 'melon-like') >>> key_list=['yuck!','tasty','smoothie'] >>> tst['taste'] = tst.get('taste') + tuple(key_list) >>> tst {'taste': ('sweet', 'sour', 'juicy', 'melon-like', 'yuck!', 'tasty', 'smoothie')}
to retrieve,
>>> tst = {'taste': ('sweet', 'sour', 'juicy', 'melon-like', 'yuck!', 'tasty', 'smoothie')} >>> taste = tst.get('taste') >>> taste ('sweet', 'sour', 'juicy', 'melon-like', 'yuck!', 'tasty', 'smoothie') >>> 'sour' in taste true >>> 'sour1' in taste false
Comments
Post a Comment