I'm writing python after writing clojure for a while, and I'm a little rusty, but I am approaching it in a much more functional style. To follow a pattern I used in clojure, I want to use map (or list comprehension) with something like assoc to set keys in each dict in a list.
I have a list of records, and I want to restructure them with list comprehensions.
The record looks like this:
{
"timestamp":1232435235315,
"data": {
"foo": 2345,
"bar": 1454
}
}
I want to get a dict containing the timestamp and the keys from data.
newlist = [ assoc(x, "timestamp", x["timestamp"]) for x in mylist ]
I could implement an assoc pretty easily, but I'd like for it to exist already in a library:
def assoc(coll, k, v):
newcoll = coll.copy()
newcoll[k] = v
return newcoll
Does anyone out there know a library which already contains something like this or a pythonic way to do it concisely without mutating the original list?
Any object, such as dictionary, can be the return value of a Python function.
In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value.
Method 1: Add new keys using the Subscript notation This method will create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn't exist, it will be added and will point to that value. If the key exists, the current value it points to will be overwritten.
The get() method returns the value for the specified key if the key is in the dictionary.
Sure, you can simply use dict()
, for example:
old = {"a": 1}
new_one = dict(old, new_key=value)
#or
new_one = dict(old, {...})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With