Max Powers
Max Powers

Reputation: 1179

loop multiple key value pairs in python dict in single loop

I have a dictionary where it has two key and value pairs such as

myDict = {'Key1':'Value1', 'Key2':'Valye2'}

I want to loop over key1 and key2 in a single loop so i can print the values of key1 and key2.

I'm able to do something like this, but this is printing the keys one by one I want print both keys in a single pass.

for key, value in myDict.items():
    print(value)

# looking to print both keys values something like this.
for key, value in myDict.items():
        print(Value1, value2)

Upvotes: 1

Views: 825

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With str.join() function:

myDict = {'Key1':'Value1', 'Key2':'Valye2'}
print(' '.join(myDict.values()))

The output:

Value1 Valye2

If you definitely assured that your dict has only 2 items, you may do the following:

b,a = myDict.values()
print(a,b)   # Value1 Valye2

Upvotes: 3

Related Questions