Python - add a list of dictionary in a dictionary - python

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)

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

Update dicitonary key with every value from a list

Given this list:
pc = ['OferteConfigurabile_S2D_Rate',
'OferteConfigurabile_S2D_Rate_si_Discount',
'OferteConfigurabile_S2D_SimOnly_si_Discount',
'OferteConfigurabile_S2D_SimOnly',
'OferteConfigurabile_S2D_VMM_Rate']
And this dictionary:
lst = []
dataModel = {
'channel': 'RETAIL',
'searchType': 'MSISDN',
'searchValue': 727277696,
'configType': 'RETENTIE',
'scenarioName_PC': 'OferteConfigurabile_ServiceOnly',
'retention_option': '360_OFERTE_MOBILE',
'retention_flow': 'ConfigureazaOferte',
}
I want for every element in the 'pc' list to update dateModel['scenarioName_PC'] and store the resulting dictionary into a list but slightly changed by creating a new dict with a custom key and dataModel dictionary as its value
for i in pc:
dataModel['scenarioName_PC'] = i
lst.append({f"{dataModel['retention_option']}_{dataModel['retention_flow']}_{i}" : dataModel})
print(lst)
The problem is that when i print the list 'scenarioName_PC' key always has the last element from the iterated list, the dataModel dictionary dosen't save the value for every for loop iteration, it somehow only stores the last value in PC list
[
{
"360_OFERTE_MOBILE_ConfigureazaOferte_OferteConfigurabile_S2D_Rate":{
"channel":"RETAIL",
"searchType":"MSISDN",
"searchValue":727277696,
"configType":"RETENTIE",
"scenarioName_PC":"OferteConfigurabile_S2D_VMM_Rate",
"retention_option":"360_OFERTE_MOBILE",
"retention_flow":"ConfigureazaOferte"
}
},
{
"360_OFERTE_MOBILE_ConfigureazaOferte_OferteConfigurabile_S2D_Rate_si_Discount":{
"channel":"RETAIL",
"searchType":"MSISDN",
"searchValue":727277696,
"configType":"RETENTIE",
"scenarioName_PC":"OferteConfigurabile_S2D_VMM_Rate",
"retention_option":"360_OFERTE_MOBILE",
"retention_flow":"ConfigureazaOferte"
}
},
Expected result is a list with dataModel dictionary but for scenarioname_PC key to have every time 'i' as value.
[
{
"360_OFERTE_MOBILE_ConfigureazaOferte_OferteConfigurabile_S2D_Rate":{
"channel":"RETAIL",
"searchType":"MSISDN",
"searchValue":727277696,
"configType":"RETENTIE",
"scenarioName_PC":"OferteConfigurabile_S2D_Rate",
"retention_option":"360_OFERTE_MOBILE",
"retention_flow":"ConfigureazaOferte"
}
},
{
"360_OFERTE_MOBILE_ConfigureazaOferte_OferteConfigurabile_S2D_Rate_si_Discount":{
"channel":"RETAIL",
"searchType":"MSISDN",
"searchValue":727277696,
"configType":"RETENTIE",
"scenarioName_PC":"OferteConfigurabile_S2D_Rate_si_Discount",
"retention_option":"360_OFERTE_MOBILE",
"retention_flow":"ConfigureazaOferte"
}
},
while appending copy the dictionary object instead of just passing the dictionary. You are passing the dictionary reference which is being modified.
This should work.
import copy
for i in pc:
new_dataMode = copy.deepcopy(dataMode)
new_dataModel['scenarioName_PC'] = i
lst.append({f"{new_dataModel['retention_option']}_{new_dataModel['retention_flow']}_{i}" : new_dataModel})
print(lst)

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]

Remove entire JSON object if it contains a specified phrase (from a list in python)

Have a JSON file output similar to:
{
"object1": {
"json_data": "{json data information}",
"tables_data": "TABLES_DATA"
},
"object2": {
"json_data": {json data information}",
"tables_data": ""
}
}
Essentially, if there is an empty string for tables_data as shown in object2 (eg. "tables_data": ""), I want the entire object to be removed so that the output would look like:
{
"object1": {
"json_data": "{json data information}",
"tables_data": "TABLES_DATA"
}
}
What is the best way to go about doing this? Each of these objects correspond to a separate index in a list that I've appended called summary[].
To achieve this, you could iterate through the JSON dictionary and test the tables_data values, adding the objectX elements to a new dictionary if their tables_data value passes the test:
new_dict = {k: v for k, v in json_dict.items()
if v.get("tables_data", "") != ""}
If your JSON objectX is stored in a list as you say, these could be processed as follows using a list comprehension:
filtered_summary = [object_dict for object_dict in summary
if object_dict.get("tables_data", "") != ""]
Unless you have compelling reasons to do otherwise, the pythonic way to filter out a list or dict (or any iterable) is not to change it in place but to create a new filtered one. For your case this would look like
raw_data = YOUR_DICT_HERE_WHEREVER_IT_COMES_FROM
# NB : empty string have a false value in a boolean test
cleaned_data = {k:v for k, v in raw_data.items() if not v["table_data"]}

Updating values in a json sting

This is the string I am looking to update.
Koordinatstring =
{
"Koords":"Koordinates",
"TrueCoords":
{
"FirstFind":
{
"X":"134",
"Y":"223",
},
"SecondFind":
{
"X":"721",
"Y":"632",
},
"ThirdFind":
{
"X":"412",
"Y":"344",
},
"FourthFind":
{
"X":"612",
"Y":"532",
}
}
}
I know how to extract only the X or Y value from FourthFind for example. But what I am looking to do at the moment, is to access that value and replace it with a new one that I want to input.
I would like to do something simliar to:
k = json.dumps(koordinatstring)
l = json.loads(k)
Kords1 = l['TrueCoords']['FirstFind']['X']
To overwrite data, but I don't know if that is possible.
Even though the data may have come from a JSON document, once parsed you have ordinary dictionaries referencing other ordinary dictionaries.
You can always assign to a key in a dictionary:
d = {'foo': 'bar'}
d['foo'] = 'spam'
You just have a nested dictionary, so you need to string together a few [...] subscriptions to access the one you want to change:
l['TrueCoords']['FourthFind']['X'] = '42'
This sets the 'X' key to the new value '42', in the dictionary referenced by l['TrueCoords']['FourthFind'].

Categories