views:

144

answers:

4

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

+2  A: 

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

Peter Stuifzand
+4  A: 

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()

Paolo Bergantino
+3  A: 

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.

Paul Fisher
Ah, I see what I did, but I am still unsure how to fix it. When I was getting the name of the function and using a regex, I used the .groups() method. I'll add the code for that in the original, because I casted it to a str, and it still yields the same output
Justen
If you used .groups(), try just using .group()
Paolo Bergantino
that worked. Thanks a lot!
Justen
err.. no problem.
Paolo Bergantino
+1  A: 

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)
+1 a good point.
Paolo Bergantino