How to duplicate nested dictionaries without aliasing? - python

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')
}

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 extract info from the dictionaries within a list?

I'm new to Python, trying to gather data from a json file that consists of a list that contains info inside dictionaries as follows. How do I extract the "count" data from this? (Without using list comprehension)
{
"stats":[
{
"name":"Ron",
"count":98
},
{
"name":"Sandy",
"count":89
},
{
"name":"Sam",
"count":77
}
]
}
Index the list using the stats key then iterate through it
data = {
"stats":[
{
"name":"Ron",
"count":98
},
{
"name":"Sandy",
"count":89
},
{
"name":"Sam",
"count":77
}
]
}
for stat in data['stats']:
count = stat['count']
Consider the dictionary data stored in a variable source.
source = {
"stats":[
{
"name":"Ron",
"count":98
},
{
"name":"Sandy",
"count":89
},
{
"name":"Sam",
"count":77
}
]
}
Now to access the count field inside of "stats" we use indexing.
For example, to view the count of "Ron" you would write:
print(source['stats'][0]['count'])
This will result in 98
Similarly, for "Sam" it will be
print(source['stats'][2]['count'])
And the result will be 77
In short, we first index the key of dictionary, then the array position and then provide the filed from array of which you want the data.
I hope it helped.
Simply append all those values to do calculations:
count_values = []
for dic in data['stats']:
count_values.append(dic['count'])
# Do anything with count_values
print(count_values)
According to the Zen of Python, "Simple is better than complex."
Thus, list comprehension is actually the best way to extract the information you need and still have it available for further processing (in the form of a list of count values).
d = <your dict-list>
count_data_list = [ x['count'] for x in d['stats'] ]
If not, and your intention is to process the "count" data as it is extracted, I'd suggest a for-loop:
d = <your dict-list>
for x in d['stats']:
count_data = x['count']
<process "count_data">
using a map function will do that in a single line
>>> result = list(map(lambda x: x['count'], data['stats']))
[98, 89, 77]

How can I iterate a dictionary which is into another dictionary to get specific values?

I'm trying to iterate a dictionary that is into another dictionary to get 2 values (content and completed_date) of each set but I don't know how to do it. This is the data:
{
'items':[
{
'content':'Get a solution for the server #connect',
'meta_data':None,
'user_id':20440353,
'task_id':3186948449,
'project_id':2203217746,
'completed_date':'Tue 07 May 2019 18:31:47 +0000',
'id':3186948449
},
{
'content':'Fix the Placement test based on the feedback #connect',
'meta_data':None,
'user_id':20440353,
'task_id':3186363895,
'project_id':2203217746,
'completed_date':'Tue 07 May 2019 14:52:27 +0000',
'id':3186363895
}
],
'projects':{
}
}
This is what I've been trying:
>>> for items in itstuff_data['items']:
... print(items)
...
But is giving me everything inside of 'items' (as expected). Is there a way to iterate the data to get just content and completed_date?
In your loop, items will probably always be a dictionary; to now access the "content" and the "completed_date", you can just index into that dictionary:
items["content"]
items["completed_date"]
here is one way, you just need to loop again!
itstuff = {
'items':[
{
'content':'Get a solution for the server #connect',
'meta_data':None,
'user_id':20440353,
'task_id':3186948449,
'project_id':2203217746,
'completed_date':'Tue 07 May 2019 18:31:47 +0000',
'id':3186948449
},
{
'content':'Fix the Placement test based on the feedback #connect',
'meta_data':None,
'user_id':20440353,
'task_id':3186363895,
'project_id':2203217746,
'completed_date':'Tue 07 May 2019 14:52:27 +0000',
'id':3186363895
}
],
'projects':{
}
}
for obj in itstuff["items"]:
for key in obj:
if (key == "content" or key == "completed_date"):
# Do something with values
print(obj[key])
This is a good use-case for operator.itemgetter:
from operator import itemgetter
# foo(d) == (d['content'], d['completed_date'])
foo = itemgetter("content", "completed_date")
for content, completed_date in map(foo, itstuff_data['items']):
...
data=[]
for dic in itstuff_data['items']:
data.append((dic['content'],dic['completed_date']))
print(dic['content'],dic['completed_date'])
you can also iterate through a dictionary object as
for k,v in dic.items() or for item in dic: print(dic[item])

Python - add a list of dictionary in a dictionary

So I have a dictionary called component and a list of dictionaries called allocations.
I want to be able to put the allocations under a component as a nested dictionary. kind of like so:
Allocations[
allocation1 : {
key : value
},
allocation2 {
key : value
}
]
My desired output:
Component1 : {
key:value
allocations : [allocation1 : {
key : value
}
,allocation2 : {
key : value
}
]
}
I came from Java, and i realize there is no append that I can use.
I tried this and obviously didnt work:
#allocate this under the selected component - DIDNT WORK
component["allocations"][] = allocation
How can I create a list of dictionaries in a dictionary?
Simply assign it:
component["allocations"] = some_list
For instance, if you want a new, empty one:
component["allocations"] = []
or:
component["allocations"] = list()
Then, manipulate the list as usual:
component["allocations"].append(some_object)

Indexing down multiple levels in Python

I know this is probably a pretty basic one, but I've looked and I can't find the answer.
I have a system running trees (nested dict objects) that can be of arbitrary depth.
At present, a subtree index is stored as a list of keys, so in the structure:
example = { 1 : "foo" ,
2 : { 2 : "bar" } ,
3 : { 3 : { 3 : "zip" } } }
the index of "foo" is [1], the index of "bar" is [2,2] and the index of "zip" is [3,3,3].
At the moment, I'm iterating through the list with a for loop :
pointer = root_of_tree
for index in index_list :
pointer = pointer[index]
This works pretty well, but it strikes me that Python is the sort of language that might have a built-in way of handling this case.
Is there a one-line solution? Perhaps a method of the iterable class?

Categories