0

I have available to me tags and data from a dict that I use in the following way:

tags_df_map = zip(tags, data)
append_series = [series for tags,series in tags_df_map if tags['Index'] =='A']
append_tags = [tags['Index'] for tags, series in tags_df_map if tags['Index'] =='A']
series_to_append = dict(zip(append_tags,append_series))

Is there an easier and more efficient method in Python to arrive at series_to_append dict? Thanks in advance

sg91
  • 175
  • 1
  • 1
  • 11

1 Answers1

0

You can use a dictionary comprehension:

series_to_append = {tag[my_key]: series for tag, series in zip(tags, data) 
                    if tag['Index'] == 'A'}

Note that I am using an arbitrary variable my_key as the key I'm using to access tag for generating the keys of the dictionary comprehension. Before, you had used tag['Index'] to create the keys for series_to_append. This will result in series_to_append having only one key ('A'), since you are only using values in which tag['Index'] is equal to 'A'.

Here is an example of this dictionary comprehension in use:

data = [0,1,2,3,4,5,6]
tags = [{'Index': 'A', 'Key': chr(x+65)} if x % 2 == 0 else {'Index': 'B', 'Key': chr(x+65)} 
        for x in range(7)]

# the original code snippet
tags_df_map = zip(tags, data)
append_series = [series for tag, series in tags_df_map if tag['Index'] =='A']
append_tags = [tag['Index'] for tag, series in tags_df_map if tag['Index'] =='A']
series_to_append = dict(zip(append_tags,append_series))
print(series_to_append)
>> {'A': 6}

{tag['Index']: series for tag, series in zip(tags, data) 
                    if tag['Index'] == 'A'}
>> {'A': 6}

{tag['Key']: series for tag, series in zip(tags, data) 
                    if tag['Index'] == 'A'}
>> {'A': 0, 'C': 2, 'E': 4, 'G': 6}

Also, as a warning, since it appears that you are using Python 2, using tags as a variable name inside your comprehensions will result in the variable tags pointing to the last value it was assigned inside the comprehension (rather than the value it pointed to before). That is, assigning a value to a variable inside a list comprehension is treated the same as variable assignment outside of the list comprehension. It's worth noting that this doesn't happen in Python 3 due to how comprehensions are scoped, but it is still usually good practice to not reuse a variable name inside a comprehension unless there is a good reason for doing so.

D. Gillis
  • 670
  • 5
  • 8