I want to output my key value pairs from a python dictionary as such:
key1 t value1 key2 t value2
I thought I could maybe do it like this:
for i in d:
print d.keys(i), d.values(i)
but obviously that’s not how it goes as the keys() and values() don’t take an argument.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Python 2 and Python 3
i is the key, so you would just need to use it:
for i in d:
print i, d[i]
Python 3
d.items() returns the iterator; to get a list, you need to pass the iterator to list() yourself.
for k, v in d.items():
print(k, v)
Python 2
You can get an iterator that contains both keys and values. d.items() returns a list of (key, value) tuples, while d.iteritems() returns an iterator that provides the same:
for k, v in d.iteritems():
print k, v
Method 2
A little intro to dictionary
d={'a':'apple','b':'ball'}
d.keys() # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')
Print keys,values method one
for x in d.keys():
print(x +" => " + d[x])
Another method
for key,value in d.items():
print(key + " => " + value)
You can get keys using iter
>>> list(iter(d)) ['a', 'b']
You can get value of key of dictionary using get(key, [value]):
d.get('a')
'apple'
If key is not present in dictionary,when default value given, will return value.
d.get('c', 'Cat')
'Cat'
Method 3
Or, for Python 3:
for k,v in dict.items():
print(k, v)
Method 4
The dictionary:
d={'key1':'value1','key2':'value2','key3':'value3'}
Another one line solution:
print(*d.items(), sep='n')
Output:
('key1', 'value1')
('key2', 'value2')
('key3', 'value3')
(but, since no one has suggested something like this before, I suspect it is not good practice)
Method 5
for key, value in d.iteritems():
print key, 't', value
Method 6
You can access your keys and/or values by calling items() on your dictionary.
for key, value in d.iteritems():
print(key, value)
Method 7
If you want to sort the output by dict key you can use the collection package.
import collections
for k, v in collections.OrderedDict(sorted(d.items())).items():
print(k, v)
It works on python 3
Method 8
>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
... print kv[0],'t',kv[1]
...
a 1
c 3
b 2
Method 9
In addition to ways already mentioned.. can use ‘viewitems’, ‘viewkeys’, ‘viewvalues’
>>> d = {320: 1, 321: 0, 322: 3}
>>> list(d.viewitems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.viewkeys())
[320, 321, 322]
>>> list(d.viewvalues())
[1, 0, 3]
Or
>>> list(d.iteritems()) [(320, 1), (321, 0), (322, 3)] >>> list(d.iterkeys()) [320, 321, 322] >>> list(d.itervalues()) [1, 0, 3]
or using itemgetter
>>> from operator import itemgetter >>> map(itemgetter(0), dd.items()) #### for keys ['323', '332'] >>> map(itemgetter(1), dd.items()) #### for values ['3323', 232]
Method 10
A simple dictionary:
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
To print a specific (key, value) pair in Python 3 (pair at index 1 in this example):
for e in range(len(x)):
print(([x for x in x.keys()][e], [x for x in x.values()][e]))
Output:
('X', 'yes')
('Y', 'no')
('Z', 'ok')
Here is a one liner solution to print all pairs in a tuple:
print(tuple(([x for x in x.keys()][i], [x for x in x.values()][i]) for i in range(len(x))))
Output:
(('X', 'yes'), ('Y', 'no'), ('Z', 'ok'))
Method 11
To Print key-value pair, for example:
players = {
'lebron': 'lakers',
'giannis': 'milwakee bucks',
'durant': 'brooklyn nets',
'kawhi': 'clippers',
}
for player,club in players.items():
print(f"n{player.title()} is the leader of {club}")
The above code, key-value pair:
'lebron': 'lakers', - Lebron is key and lakers is value
for loop – specify key, value in dictionary.item():
Now Print (Player Name is the leader of club).
the Output is:
#Lebron is the leader of lakers #Giannis is the leader of milwakee bucks #Durant is the leader of brooklyn nets #Kawhi is the leader of clippers
Method 12
If you’re looking for pretty-printing a dictionary, check out Rich:
from rich import print
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3,
"strawberry": 1,
"blueberry": 0.5,
"mango": 4.5
}
print(prices)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
