nchuang nchuang - 1 year ago 110
Python Question

How to dynamically append to array in dict?

This has taken me over a day of trial and error. I am trying to keep a dictionary of queries and their respective matches in a search. My problem is that there can be one or more matches. My current solution is:

will already have the first match but if it finds another match it will append it using the code below.

temp5=[] #temporary variable to create array
if isinstance(match5[query_site],list): #check if already a list
match5[query_site]=temp5 #add new location

That if statement is literally to prevent extend converting my str element into an array of letters. If I try to initialize the first match as a single element array I get
if I try to directly append. I feel like there should be a more pythonic method to achieve this without a temporary variable and conditional statement.

Update: Here is an example of my output when it works

5'flank: ['8_73793824', '6_133347883', '4_167491131', '18_535703', '14_48370386']
3'flank: X_11731384

There's 5 matches for my "5'flank" and only 1 match for my "3'flank".

Answer Source

So what about this:

if query_site not in match5:  # here for the first time
   match5[query_site] = [match_site]
elif isinstance(match5[query_site], str):  # was already here, a single occurrence
    match5[query_site] = [match5[query_site], match_site]  # make it a list of strings
else:  # already a list, so just append
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download