Modify dictionary in Python - python-2.7

I have the following dictionary:
DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC",
"key4": "AAA"}]}
I want to change "records" with for example "XX" so I will have the following:
DATA = {"XX": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4":
"AAA"}]}
How can I do this? Thank you.

You can't change a string dictionary key directly in the way you have presented. The reason for this is that the key itself- which again, is a string, or str object- is immutable. This would not necessarily be true for other types of keys, such as for a user-defined object.
Your only option is to add the new key to the existing dictionary, or create a new dictionary with the key you want.
You can assign a new dictionary to the same name, DATA, and add the entry you want to the new dictionary (the old one will eventually be garbage collected):
DATA = {'XX': DATA['records']}
IMPORTANT: Note that any other references to the old DATA dictionary will NOT be updated! For this reason, the new dictionary approach is probably not what you want.
Alternatively, if it is acceptable to keep the records key in your dictionary, you can simply add the XX member to the dictionary and point it to the same value:
DATA['XX'] = DATA['records']
Lastly, if you both want to keep the original dictionary AND remove the records key from it, you will have to do that in two steps:
DATA['XX'] = DATA['records']
del DATA['records']
OR:
DATA['XX'] = DATA.pop('records')
Note that the last suggestion still occurs in two steps even though it is one line of code.

Related

pickle.dumps output size increases when input is generated using json.loads

In Python 2.7.16:
import json
import pickle
list1 = [{u'key': 1}, {u'key': 2}]
list2 = json.loads('[{"key": 1}, {"key": 2}]')
pickle.dumps(list1)
# outputs '(lp0\n(dp1\nVkey\np2\nI1\nsa(dp3\ng2\nI2\nsa.'
pickle.dumps(list2)
# outputs '(lp0\n(dp1\nVkey\np2\nI1\nsa(dp3\nVkey\np4\nI2\nsa.'
Why is the output of pickle.dumps different for list1 and for list2?
The output of pickle.dumps(list1) only contains the string key once, despite key being present in both list entries, so there appears to be some optimisation there. However, the output of pickle.dumps(list2) contains two instances of the string key.
It turns out this is due to string interning. In list1, both keys "key" are pointing to the same memory address because Python has interned the strings. In list2, the keys have different memory addresses, which suggests that json.loads does not do any string interning.
In case anyone has a similar use case to us (which is to minimise the memory footprint of an object loaded from JSON), simplejson appears to use string interning.

Flutter: Create map from list using a delimiter

I am trying to store a list of activities with a specific color locally and trying to convert the list into either a map or a list of lists.
Using shared preferences to save the data locally I have the following list:
List<String> value = ['Sleep: Blue', 'Meditation: Green', 'Running: Red'];
prefs.setStringList('ActivityList', value); //save data locally
But I want to be able to retrieve an object of the form:
values = [ {'Sleep', 'Blue'}, {'Meditation', 'Green'}, {'Running', 'Red'} ];
What would be the best way to do this and how would I use the delimiter ':' to split the data accordingly?
Thanks in advance!
I am not sure what you mean by array of objects. If you simply want an array of pairs, then the following should work for you
value.map((item) => item.split(": "))
Or if you want a key value map from your data, then you can do something like this:
Map.fromEntries(value.map((item) {
List<String> pair = item.split(": ");
return MapEntry(pair[0], pair[1]);
}));

Loop through dict key equals to list than put in new list

I have a rather large dictionary right now that is set up like this:
largedict = {'journalname':{code: 2065},'journalname1':{code: 3055}}
and so on and so on. And another dictionary:
codes = {3055: 'medicine',3786: 'sciences'}
And I want to loop through largedict, compare it's code value to the keys in codes. Then either add all journalname key/value pairs that match the code to a different dictionary, or delete all that don't from largedict.
new_dic = {journal_name : journal_body for journal_name, journal_body in largedict.items() if journal_body["code"] in codes}

How to print keys from a dictionary backwards

I have a dictionary in which I want to read each individual key backwards until it reaches the underscore. Once it reaches the underscore, it should stop so I can set its item equal to a new variable.
I understand that I can use str.partition() to seperate at a certain character and that I can use [::-1] to read a string backwards, but I am not sure how to use them together with a dictionary.
Payload_Values = {'Voltage_asleep(V)' : 10, 'Current_asleep(A)' : 5, 'Wattage_asleep' : 50}
for c in (Payload_Values.keys())
Payload_Values.partition(_)
You need to iterate a dict with keys() or items(), not iteritems(), in Python3 you need to convert these iterators to lists, otherwise it results an error if you add new element to the dict while iterating (I am just mentioning, this was ok in your example). Otherwise, you are close to the solution. I just do not understand completely, what do you want to do with the key? Print it? Take the part after the last underscore? Set a new key-value pair? Without knowing this, I am trying to present all combinations, please ask more specific if you need something else:
# this is because Python3 compatibility:
from __future__ import print_function
from future.utils import iteritems
for key, val in iteritems(Payload_Values):
# new key is the part after the last underscore
# or the whole string, if it does not contain underscore:
new_key = key.split('_')[-1]
# new key is the elements separated by `_`, reversed
# and rearranged to a string:
key_rev = '_'.join(key.split('_')[::-1])
# new key is the complete string reversed:
new_key = key[::-1]
#
# set a new element with the new key:
Payload_Values[new_key] = 'your new value'
# print the new key:
print(new_key)
# if you want to modify the dict in this loop:
for key, val in list(Payload_Values.items()):
# ...
Payload_Values[some_key] = some_value

Print key of list w/o knowing its position

I have a list that contains many keys:
mylist = {"a", "b", "c", "1", "2", "3", ...}
and I want to print the key for example that has value "x", without knowing it's exact position in the list. That mean I have to run the whole list and till "x" is found and print it. How could I do this? Seems easy question but it confuses me a bit... Thanks a lot
for key, value in pairs(mylist) do
if value == "x" then print(key) end
You can also create another mapping, eg.
mapping_list = {}
for key, value im pairs(mylist) do
mapping_list[value] = key
(assuming that list elements are unique) then, you'd be able to
print(mapping_list["x"])