Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
looping a dictionary
#1
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
buran write Apr-11-2021, 07:25 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
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
harmans14 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  making list in looping a dictionary glennford49 9 1,165 Jun-25-2020, 03:23 PM
Last Post: ndc85430
  not not working looping through a dictionary rtbr17 2 961 Oct-04-2018, 01:37 PM
Last Post: rtbr17
  Looping through dictionary and comparing values with elements of a separate list. Mr_Keystrokes 5 1,649 Jun-22-2018, 03:08 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020