callum_wostershire callum_wostershire - 8 days ago 5
Python Question

How to print first side/part of a dictionary?

consider this regular python dictionary:

Norm_Dict = {
"x" : "y"
"m" : "n"
}


and so on

My question is how to print the first part of the dictionary (how to print the "x" or the "m")

it is simple to print the secondary statement using formating such as:

print Norm_Dict["x"]


or so such
but how do you print the other value?

Answer

I am not sure which element you want to print. In your example, you want to print the value by giving the key (x), but you didn't mention anything about what you want to print.

Anyway, you can find all keys by the iterator of the dictionary.

for key in Norm_Dict:
  print (key)

or if you want to 'get' key-value pair at the same time, use

for (key, value) in Norm_Dict.items():
  print ('%r: %r' % (key, value))

And remember that keys are unique, but values are not. So basically there are no direct ways to use a value to find corresponding keys since this is not what dict is expected to be used. If you need such functions, you have to travel all the dict and record the matching keys by yourself.

Comments