Python: Append a list to an existing list assigned to a key in a dictionary?
Question: Lets say I have a dict with key= 'keys'

    
    
    >>> keys
    'taste'
    

After a 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 I want to know is, is there a way to lets say I have `agent= {'taste':
('sweet', 'sour', 'juicy', 'melon-like')}`

I want to add to a 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 a way to that?

Inshort:

  1. I want to add a list to an existing list,which is a value to a key in a dictionary (w/o iterations to find that particular key) 
  2. Check if the element being fed in as a list already contains that element in that list which is a value to a particular key, say 'taste' here (could be string, as here)


Answer: Check this out:

    
    
    >>> tst =  {'taste': ('sweet', 'sour', 'juicy', 'melon-like')}
    >>> tst.get('taste', ()) #default to () if does 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
    

