Update dicitonary key with every value from a list - python

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)

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

Difficulty understanding changes to dictionary

I was looking through old posts in order to find a method of changing values in a dictionary by iterating through the items.
dictionary = {
1: [
{
"id": "1234",
"cow": "parts/sizes/lakes"
},
{
"id": "5151",
"cow": "minors/parts"
}
]}
def fetchanswers():
for item in dictionary[1]:
yield(item["id"], item["cow"])
for a, b in fetchanswers():
k = {}
k["id"] = a
k["cow"] = b.replace("parts", a)
My understanding is that yield returns the two items from either object in the dictionary and the for loop creates a new dictionary and appends the values obtained from fetchanswers() and parts is replaced by id.
I don't understand how k["id"] can be referred to when the dictionary is empty.
a method of changing values in a dictionary
Your values are strings. Strings are immutable, so you need to overwrite the dictionary using existing keys
You don't need another dictionary for this
# replace "parts" text value with the value of the id key
for item in list_of_dicts:
item["cow"] = item["cow"].replace("parts", str(item["id"]))
how k["id"] can be referred to
It's not a referral when there's an equal sign afterwards. It's an assignment

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)

Store two values from JSON_file in new dictionary with python

I want to store two values from JSON_file in new dict like this : {[1,2,5]:[0], [1,2,4]:[2]}
my JSON-file looks like this :
{
"index": [
{
"timestamp": "2018-04-17 17:56:25",
"src": "src",
"dst": [1,2,5],
"value": [0],
"datatype": "datatype"
},
{
"timestamp": "2018-04-17 18:00:43",
"src": "src",
"dst": [1,2,4],
"value": [2],
"datatype": "datatype"
}
]
}
I wrote this code:
with open(filename) as feedjson:
json_data = json.load(feedjson)
feedjson.close()
list_dev = {}
for i in json_data["index"]:
key = i['value']
value = i['dst']
list_dev[key] = value
print(list_dev)
I get this error:
list_dev.update({key: value})
TypeError: unhashable type: 'list'
can someone help me to fix this problem please?
This is just for understanding purposes:
Dictionary keys should be immutable as explained here. In the question, [1,2,5] is a list which are mutable(contents can be modified with methods like append,pop, push) data types. So, the only way to use the entire contents of a list as a dictionary key(highly unusual) is to convert it to an immutable data type such as a tuple or string:
new_dict = {} #initialize empty dictionary
dst = t['index'][0]['dst'] #[1,2,5]
value = t['index'][0]['value'] #[0]
new_dict[tuple(dst)] = value #new_dict key "dst" as tuple
print(new_dict)
--->{(1, 2, 5): [0]}
new_dict[str(dst)] = value #new_dict key "dst" as string
print(new_dict)
---->{'[1, 2, 5]': [0]}
value is a list -> [1] or [2] or whatever, list is mutable object so you can't hash it
you can use the element in the list like
key=i['value'][0]
or convert the list to tuple like
key=tuple(i['value'])
both objects are immutable thus can be hashed and used as a key
by the way with provide context manager so you don't need to close the file using feedjson.close(), with will do it for you

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