Python Forum

Full Version: looping a dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Trying to understand this piece of code. Would appreciate any help
  job_args = dict()
    if args.job_args:
        job_args_tuples = [arg_str.split('=') for arg_str in args.job_args]
        job_args = {a[0]: a[1] for a in job_args_tuples}
So in the first line, we create a dictionary of job_args. Can someone please explain line 3 and 4?

thanks
The first line creates an empty dict and assigns it to the name job_args.

The third line is a list comprehension, a compact way of gathering the output of a looping construct in a list. The line could be "unrolled" and replaces something like this:

temp_list = []
for arg_str in args.job_args:
    temp_list.append(arg_str.split("="))
job_args_tuples = temp_list
The fourth line is similar, but it is a dict comprehension instead of a list comprehension.

temp_dict = {}
for a in job_args_tuples:
    temp_dict[a[0]] = a[1]
job_args = temp_dict