Reputation: 205
So I have trouble to print out two value that are from a list that I have created.
Basically I did a list of:
[
{
'Numbers': '1',
'Name': 'Hello'
},
{
'Numbers': '2',
'Name': 'There'
},
{
'Numbers': '3',
'Name': 'Stack'
},
{
'Numbers': '4',
'Name': 'OVerflow'
}
]
Right now if I basically call that function which is
names_number()
It would give me that values.
So of course you would use a for loop which will print each of these for its own so in that case a loop that looks like:
for i in names_number(): print(i)
That would give me:
{'Numbers': '1', 'Name': 'Hello'}
{'Numbers': '2', 'Name': 'There'}
{'Numbers': '3', 'Name': 'Stack'}
The problem now is that I want it to print out only
1 Hello
2 There
3 Stack
and I have no idea how I would in that case print out just the values of each of this everytime it for loops. I would appreciate any tip or solution on how I can continue to make a output like I wish above
Upvotes: 1
Views: 462
Reputation: 164623
The default separator for print
is a single whitespace, so you use a simple for
loop:
for d in L:
print(d['Numbers'], d['Name'])
Or using f-strings (Python 3.6+):
for d in L:
print(f"{d['Numbers']} {d['Name']}")
Here's a convoluted functional solution:
from operator import itemgetter
fields = ('Numbers', 'Name')
print(*(f'{num} {name}' for num, name in map(itemgetter(*fields), L)), sep='\n')
1 Hello
2 There
3 Stack
4 OVerflow
Upvotes: 2
Reputation: 5274
I would probably do something like this:
item_list = [
{
'Numbers': '1',
'Name': 'Hello'
},
{
'Numbers': '2',
'Name': 'There'
},
{
'Numbers': '3',
'Name': 'Stack'
},
{
'Numbers': '4',
'Name': 'OVerflow'
}
]
for item in item_list:
print (" ".join([item["Numbers"], item["Name"]]))
Which produces:
1 Hello
2 There
3 Stack
4 OVerflow
Pretty much looping the list, and the printing out the key/value pairs.
Upvotes: 1
Reputation: 594
I would do it like this:
for doc in lst:
print(doc['Numbers'], doc['Name'])
Wich produces the desired out
Upvotes: 0
Reputation: 15204
How about that:
for dct in lst:
print('{} {}'.format(dct['Numbers'], dct['Name']))
which produces the desired:
1 Hello
2 There
3 Stack
4 OVerflow
Note that if you did not care about the order of the items (1 Hello
or Hello 1
), or if you are using Python 3.6+ you can use the more elegant:
for dct in lst:
print('{} {}'.format(*dct.values()))
Upvotes: 1