Justen
Justen

Reputation: 4869

Formatting the output of a key from a dictionary

I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?

for f_name,f_loc in dict_func.items():
        print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc))

output:

Enter the file name: test.txt
line = 'def count_loc(infile):'

There were 19 lines of code in "test.txt"

Function names:

    ('count_loc(infile)',) -- 15 lines of code

Just incase it wasn't clear, I would like the last line of the output to be displayed as:

count_loc(infile) -- 15 lines of code

EDIT

name = re.search(func_pattern, line).groups()
name = str(name)

Using type() before my output, I verified it remains a string, but the output is as it was when name was a tuple

Upvotes: 1

Views: 482

Answers (4)

Paul Fisher
Paul Fisher

Reputation: 9666

To elaborate on Peter's answer, It looks to me like you're assigning a one-item tuple as the key of your dictionary. If you're evaluating an expression in parentheses somewhere and using that as the key, be sure you don't have a stray comma in there.

Looking at your further edited answer, it's indeed because you're using the groups() method of your regex match. That returns a tuple of (the entire matched section + all the matched groups), and since you have no groups, you want the entire thing. group() with no parameters will give you that.

Upvotes: 3

Paolo Bergantino
Paolo Bergantino

Reputation: 488694

I don't have Python 3 so I can't test this, but the output of f_name makes it look like it is a tuple with one element in it. So you would change .format(f_name, f_loc) to .format(f_name[0], f_loc)

EDIT:

In response to your edit, try using .group() instead of .groups()

Upvotes: 4

johannix
johannix

Reputation: 29658

Since the key is some type of tuple, you may want to join the different elements before printing. We can't really tell what the significance of the key is from the snippet shown.

So you could do something like such:

.format(", ".join(f_name), f_loc)

Upvotes: 1

Peter Stuifzand
Peter Stuifzand

Reputation: 5104

I expect you have a problem with your parsing code. The lines as written should work as expected.

Upvotes: 2

Related Questions