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.
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'}]
You can convert this like:
def fix_key_formatting(data_to_dump, keys_to_fix):
return_str = json.dumps(data_to_dump)
for key in keys_to_fix:
return_str = return_str.replace('"%s":' % key, '%s:' % key)
return return_str
data = [
{'name': 'red', 'id': '1'},
{'name': 'yellow', 'id': '2'},
{'name': 'black', 'id': '3'},
{'name': 'white', 'id': '4'}
]
import json
print(fix_key_formatting(data, ('id', 'name')))
[
{name: "red", id: "1"},
{name: "yellow", id: "2"},
{name: "black", id: "3"},
{name: "white", id: "4"}
]
You can create a simple class with a __repr__ method to store the string value:
class String:
def __init__(self, val):
self.val = val
def __repr__(self):
return self.val
data = [{'name' : 'red', 'id' : '1'}, {'name' : 'yellow', 'id' : '2'}, {'name' : 'black', 'id' : '3'}, {'name' : 'white', 'id' : '4'}]
final_data = [{String(c):d for c, d in i.items()} for i in data]
Output:
[{name: 'red', id: '1'}, {name: 'yellow', id: '2'}, {name: 'black', id: '3'}, {name: 'white', id: '4'}]
To access the string values, you can call the attribute:
string_values = [{c.val:d for c, d in i.items()} for i in final_data]
To apply the class String to all keys in an arbitrary structure, recursion can be used:
def convert_string(d):
return {String(a):convert_string(b) if isinstance(b, dict) else b for a, b in d.items()}
data = [{'name' : {'first':'blue', 'last':'black', 'known_ids':[34, 5, 12, 34]}, 'id' : '1'}, {'name' : 'yellow', 'id' : '2'}, {'name' : 'black', 'id' : '3'}, {'name' : 'white', 'id' : '4'}]
new_data = list(map(convert_string, data))
Output:
[{name: {first: 'blue', last: 'black', known_ids: [34, 5, 12, 34]}, id: '1'}, {name: 'yellow', id: '2'}, {name: 'black', id: '3'}, {name: 'white', id: '4'}]