Python: nested dict and specification in one key - python

I need to make a yaml file with a dict and a specific format.
The desired format of the yaml file would be:
classification:
- type: 4
probability: 1.0
So far I created a dict with the following:
dic = {
'classification': {
'type': 4,
'probability': 1.0
}
which creates the following yaml file:
classification:
type: 4
probability: 1.0
What do I need to do to get the - in front of type?

If you're using PyYAML, the hyphen gets added to the output for items within a list, so if you had:
dic = {
'classification': [ # start a list
{
'type': 4,
'probability': 1.0
}
]
}
then the output would be:
import yaml
yaml.dump(dic, sys.stdout)
classification:
- probability: 1.0
type: 4
Note that YAML seems to sort the dictionary keys alphabetically by default. To have it not sort the keys, you would instead do:
yaml.dump(dic, sys.stdout, sort_keys=False))
classification:
- type: 4
probability: 1.0

Related

how do i add key to my json list in python to an object with the same name?

hello i got a problem and i'm not sure how to solve it :
i have a project where i'm recovering a json file via a request and making a list with the keys i need so it look a bit like this:
{
"name":"Lucas White",
"project":{
"key_project":"EB-648",
"name_status":"Open"
}
},
{
"name":"Lisa Booth",
"project":{
"key_project":"EB-647",
"name_status":"Open"
}
}
{
"name":"Lucas White",
"project":{
"key_project":"EB-645",
"name_status":"Development In Progress"
}
},
here is my code in python
entries = []
entries.append({
"name":name ,
"project": {
"key_project":key_project,
"name_status":name_status
}
},)
how do i make it so that Lucas get a list with all his project keys ??
also its my first question i hope it is clear cause english is not my first language
I would suggest the next approach. First, add all data to the map and then transform the map to the list. You can use "name" as a key in the map. Here is out of a head example:
elements = {}
for ...:
...
if name not in elements:
# we check if name is not in our dictionary and create new list for that name
elements[name] = list()
elements[name].append({
"key_project":key_project,
"name_status":name_status
})
# we append the new project to the list
# as a result we get a map with names as keys and a list of projects for that name as values
result_list = [{"name": k, "projects": v} for k, v in elements.items()]
# k - key - and we used "name" as key
# v - value - value is list of all projects

How to duplicate nested dictionaries without aliasing?

In python I am looking to create nested dictionaries for a text parsing application. The data structure I have right now uses a dictionary to reference two sub dictionaries, and then each of those sub dictionaries has multiple subdictionaries, and then those subdictionaries have values. All of the innermost dictionaries have the same fields.
# innermost dictionary
specificSensorInfo = {
"value":None,
"status":None
}
# middle dictionaries
board1_sensors = {
13 : specificSensorInfo, #"AUX +3.3V Vol"
14 : specificSensorInfo, #"MCU_Temperature"
15 : specificSensorInfo, #"AUX +3.3V Temp"
}
board2_sensors = {
13 : specificSensorInfo, #"AUX +3.3V Vol"
14 : specificSensorInfo, #"MCU_Temperature"
15 : specificSensorInfo, #"AUX +3.3V Temp"
}
#outermost dictionary
all_sensor_info = {'B1':board1_sensors,
'B2':board2_sensors}
I am going to parse a text file and then set the values of the dictionary based on what is parsed. I expect to fill out the data fields like this:
all_sensor_info['B1'][13]['value'] = 10
all_sensor_info['B2'][14]['status'] = 'OK'
The problem I am finding is that when I change a value in one of the innermost dictionaries, it changes that value across all of the data. So in the above example every specificSensorInfo dictionary would show {10, 'OK'}. This is because all the dictionaries reference the same object, I think.
How can I accomplish what I'm looking for? Do I need to create a class and set attributes? I thought using dictionaries would be easier to use than classes so I can use the [] operator instead of the dot operator.
Don't reference the same dictionary 6 times, as then indeed a mutation of that single dictionary will be seen through all properties that have that reference.
Instead, create new dictionaries using the dict constructor:
# middle dictionaries
board1_sensors = {
13 : dict(specificSensorInfo), #"AUX +3.3V Vol"
14 : dict(specificSensorInfo), #"MCU_Temperature"
15 : dict(specificSensorInfo), #"AUX +3.3V Temp"
}
board2_sensors = {
13 : dict(specificSensorInfo), #"AUX +3.3V Vol"
14 : dict(specificSensorInfo), #"MCU_Temperature"
15 : dict(specificSensorInfo), #"AUX +3.3V Temp"
}
Alternatively, you can create the structure in nested loops, and -- why not -- using dictionary comprehension:
all_sensor_info = {
# middle dictionaries
code: {
# innermost dictionaries
id: {
"value":None,
"status":None
}
for id in (13, 14, 15)
}
for code in ('B1', 'B2')
}

convert list of objects to Json array

I'm new to python and i have a list of objects like this.
Sample code
>>> for val in las.version:
... print(val.mnemonic)
... print(val.unit)
... print(val.value)
... print(val.descr)
...
VERS
1.2
some description
WRAP
NO
another description
>>>
I wanted to convert this as JSON array.
{
"versionInformation":[
{
"mnemonic":"VERS",
"unit":"",
"value":"2.0",
"description":"some description"
},
{
"mnemonic":"WRAP",
"unit":"",
"value":"NO",
"description":"another description"
}
]
}
Without the HeaderItem description this cannot account for possible errors, but you can easily recreate the JSON structure using dict/list combos and then use the built-in json module to get your desired JSON, i.e.:
import json
version_info = [{"mnemonic": v.mnemonic, "unit": v.unit,
"value": v.value, "description": v.descr}
for v in las.version]
print(json.dumps({"versionInformation": version_info}, indent=3))
Keep in mind that prior to CPython 3.6 and Python 3.7 in general, the order of the items in the JSON of individual version info cannot be guaranteed. You can use collections.OrderedDict instead if that's important - it shouldn't be, tho, given that JSON by specification uses unordered mappings.
from pprint import pprint
result = {}
result['versionInformation'] = []
for val in las.version:
version_info = {}
version_info['mnemonic'] = val.mnemonic
version_info['unit'] = val.unit
version_info['value'] = val.value
version_info['description'] = val.descr
result['versionInformation'].append(version_info)
pprint(result)

Python - convert JSON object to dict

I am wondering how I can convert a json list to a dictionary using the two values of the JSON objects as the key/value pair.
The JSON looks like this:
"test": [
{
"name": "default",
"range": "100-1000"
},
{
"name": "bigger",
"range": "1000-10000"
}
]
I basically want the dictionary to use the name as the key and the range as the value. SO the dictionary in this case would be {default:100-1000} {bigger: 1000-10000}
Is that possible?
You can first load the JSON string into a dictionary with json.loads. Next you can use dictionary comprehension to post process it:
from json import loads
{ d['name'] : d['range'] for d in loads(json_string)['test'] }
We then obtain:
>>> { d['name'] : d['range'] for d in loads(json_string)['test'] }
{'bigger': '1000-10000', 'default': '100-1000'}
In case there are two sub-dictionaries with the same name, then the last one will be stored in the result.

How to add a key,value pair to a list?

I would like to be able to create a list of key, list pairs ( I think that's the most accurate way to describe my desired solution...)
I have a list of dictionaries and would like to add an element to each of these dictionaries that is a list of dictionaries (a mouthful, I know...).
To do this, I try to append key, value pairs to a list. When I do this I get a syntax error ostensibly tripped on the colon in the key:value pair.
Here's my code:
d_l[0]['abilities'] = list()
d_l[0]['abilities'].append(abilities_m_l[job_row]['Element Name']:list()) # ability: stats about ability
where d_l is a list of dictionaries, 'abilities' is a key that I am creating.
And here's my error (the caret is on the colon (although in the past it's mislabeled the location of the error)).
d_l[0]['abilities'].append(abilities_m_l[job_row]['Element Name']:list()) # ability: stats about ability
^
SyntaxError: invalid syntax
logout
If it helps, this is the desired overall structure:
{
'job':'clerk', 'description': 'works in a bank', 'abilities': [
'math': [
'imp': {
'Data Value': 4.5,
'N' : 8,
'S_E': 0.19
},
'level': {
'Data Value': 4.75,
'N': 8,
'S_E': 0.25
}
],
'english': [
'imp': {
},
'level': {
}
],
'dexterity': [
'imp':{
},
'level': {
}
]
]
},
Thanks so much! If you see obvious flaws in my arrangement just above (maybe I should be using a dictionary for abilities instead of a list?) please let me know.
You want to append a dict - note the {}, eg:
.append( {abilities_m_l[job_row]['Element Name']:list()} )
And it's more Pythonic and efficient to use [] for an empty list...

Categories