2

Currently, I'm trying to fill a dictionary in Python but I think what I'm doing is a little bit redundant. Is there a more pythonic way to do the following:

if not pattern_file_map.get(which_match):
    pattern_file_map[which_match] = [line]
else:
    pattern_file_map[which_match].append(line)

where pattern_file_map is a dictionary.

I know that there is a certain idiom to use when checking if there is a key in a dictionary, like this question, but I I just want to fill this dictionary with a lists.

Community
  • 1
  • 1
Jeffrey Greenham
  • 1,382
  • 5
  • 16
  • 33

3 Answers3

10

You could use

pattern_file_map.setdefault(which_match, []).append(line)

instead.

Other people might suggest using a collections.defaultdict(list) instead, which is another option, but be warned that this might hide errors, since it will silently create all keys you access.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
4

You could try using a collections.defaultdict.

seandavi
  • 2,818
  • 4
  • 25
  • 52
0

Since you're adding to a maybe existing value:

pattern_file_map.setdefault(which_match, []).append(line)

If using dict.get():

li = pattern_file_map.get(which_match, [])
li.append(line)
pattern_file_map[which_match] = li

Of course, both cases are restricted to the case where your dict's values are lists.

Nisan.H
  • 6,032
  • 2
  • 26
  • 26
  • What's the difference between: pattern_file_map.get(which_match, []) and pattern_file_map.setdefault(which_match, [])? – Jeffrey Greenham Jun 21 '12 at 16:50
  • `.get(key,default)` returns a value or default (without setting) and requires assignment back into the dictionary. `.setdefault(key,default)` is a better choice in this case. I corrected my answer. – Nisan.H Jun 21 '12 at 17:08