2

I read a lot of tutorials, but can not find how to iterate dict in string.format like this:

dict = {'this':'I','is':'am','title':'done'}
print(f'the key is {k for k,v in dict}')
print(f'the val is {v for k,v in dict}')

which I want a result like this:

the key is this is title
the val is I am done

so I can print variable length dict.

dict = {'this':'I','is':'am','title':'done'}
print(f'the key is {k for k,v in dict}')
print(f'the val is {v for k,v in dict}')

Then I got error.

0

3 Answers 3

2

Currently your output is:

the key is <generator object <genexpr> at 0x7fbaca5443c0>
the val is <generator object <genexpr> at 0x7fbaca5443c0>

That's because k for k,v in dict is a generator expression. Don't confuse it with set comprehension, those curly braces are for f-string.

But of course that k for k,v in dict is problematic. When you iterate over a dictionary itself, it gives you keys. So for the first iteration "this" comes back. you can't unpack "this" into two variables. k, v = "this".

You can use this:

d = {"this": "I", "is": "am", "title": "done"}
print(f'the key is {" ".join(d.keys())}')
print(f'the val is {" ".join(d.values())}')

output:

the key is this is title
the val is I am done

This join works because keys and values are strings in your dictionary. If they are not, you should convert them like:

print(f'the key is {" ".join(map(str, d.values()))}')

For the first one you could also use print(f'the key is {" ".join(d)}') as dictionaries will give keys in the iteration by default.

Sign up to request clarification or add additional context in comments.

1 Comment

@FL.S For that use: print(f'the key is {" ".join(map(repr, d.keys()))}')
0

I would do this, if you don't mind having a space at the end I'm no expert tho:

mydict = {"this": "I", "is": "am", "title": "done"}


def get_str(dict):
    str_a = ""
    str_b = ""
    for k in dict:
        str_a += f"{k} "
        str_b += f"{dict[k]} "
    print(str_a)
    print(str_b)


get_str(mydict)

output:

this is title 
I am done 

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

print("The keys are", ' '.join(k for k in dict)) for the keys

print("The keys are", ' '.join(v for k, v in dict.items())) for the values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.