nchuang
nchuang

Reputation: 93

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:

match5[query_site] 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              
    temp5.extend(match5[query_site])
    temp5.append(match_site)
else:
    temp5.append(match5[query_site])
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 None 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".

Upvotes: 1

Views: 209

Answers (4)

sal
sal

Reputation: 3593

Assuming match5 is a dictionary, what about this:

if query_site not in match5:  # first match ever
   match5[query_site] = [match_site]
else:  # entry already there, just append
   match5[query_site].append(temp5)

Make the entries of the dictionary to be always a list, and just append to it.

Upvotes: 0

j-i-l
j-i-l

Reputation: 10957

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
   match5[query_site].append(match_site)

Upvotes: 1

smac89
smac89

Reputation: 43078

This is all you need to do

if query_site not in match5:
    match5[query_site] = []
temp5 = match5[query_site]
temp5.append(match_site)

You could also do

temp5 = match5.setdefault(query_site, [])
temp5.append(match_site)

Upvotes: 0

Bill Gribble
Bill Gribble

Reputation: 1797

I like using setdefault() for cases like this.

temp5 = match5.setdefault(query_site, [])
temp5.append(match_site) 

It's sort of like get() in that it returns an existing value if the key exists but you can provide a default value. The difference is that if the key doesn't exist already setdefault inserts the default value into the dict.

Upvotes: 1

Related Questions