-2

I just started learning Python and I have a question I didn't find answer for.

There is a command that will print all keys of a dictionary ex.

list = {
 "key1": "value1",
 "key2": "value2"
}

for x in list:
   print(x)

And output will be:

key1
key2

Also there is a command that will print the value of specified key

y = list["key1"]
print(y)

And output will be:

value1

What I want to know is there any command that will print all the values of all keys the same time with one command(just like we did with keys) and not to access them one by one.

Hopefully I was clear enough, thanks.

2 Answers2

5

You can use .values:

my_dict = {
 "key1": "value1",
 "key2": "value2"
}

print(*my_dict.values(), sep='\n')

Or if you want only keys you may use .keys:

print(*my_dict.keys(), sep='\n')

Or if you want key and value pairs, you may use .items:

print(*my_dict.items(), sep='\n')

Note: Using variable name as list is not a good practice.

niraj
  • 17,498
  • 4
  • 33
  • 48
  • Yeah using var name as list for dict was my mistake, I will not make that mistake again, and that, solved my problem even though it says that my question is duplicate I checked the other question I didn't understand the code, and thank you very much – ArjanitAzemi Feb 22 '19 at 19:42
0

First of all, I wouldn't use list as a name for your dictionaries, because list is an actual Python command. But if "mydict" is the name of your dictionary, then mydict.keys() will return a list of all the keys, and mydict.values() will do the same with values. If you want to print all of these out as a single string, you could add a join command:

>>> mydict = {"key1": "value1", "key2": "value2"}
>>> ', '.join(mydict.values())
'value2, value1'
>>> print('\n'.join(mydict.values()))
value2
value1

Note that dictionaries in Python aren't sorted, so the derived lists are not necessarily going to reflect the order you entered the values in. If you wanted to alpha-numerically sort the list on the fly, you could do this:

>>> print('\n'.join(sorted(mydict.values())))
value1
value2

If however you want a dictionary that will have some sort of order in the first place, then you may want to look into Ordered Dictionaries.

Bill M.
  • 1,388
  • 1
  • 8
  • 16