Python Forum
looping a dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: looping a dictionary (/thread-33267.html)



looping a dictionary - harmans14 - Apr-11-2021

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


RE: looping a dictionary - bowlofred - Apr-11-2021

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