Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary in list

I want to print a dictionary inside a list like this :

[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]`

I don't want quotations in name and id. However, I want them in the values portion of that dictionary.

like image 478
Anmol Gautam Avatar asked Feb 06 '18 04:02

Anmol Gautam


People also ask

Can a list contain a dictionary?

Dictionaries can be contained in lists and vice versa.

Can you put a dictionary in a list Python?

Use the copy() method to create a shallow copy of the dictionary. Use the list. append() method to append the copy to the list. The list will contain the dictionary by value, and not by reference.

Can you nest a dictionary in a list?

A Python list can contain a dictionary as a list item.


1 Answers

You'd have to write your own formatting function to do that.

Here's a hairy but terse function that does what you want:

def pretty_print(data):
    return '[%s]' % ', '.join(
        '{%s}' % ', '.join(
            '%s : %r' % (key, value) for key, value in item.items()
        ) for item in data
    )

So the following code:

print(pretty_print([
    {'name': 'red', 'id': '1'},
    {'name': 'yellow', 'id': '2'},
]))

Would print:

[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}]
like image 180
rovaughn Avatar answered Oct 09 '22 06:10

rovaughn