Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a python function to return a new dict with a new key added, like assoc in clojure?

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?

like image 492
Mnebuerquo Avatar asked Oct 09 '17 13:10

Mnebuerquo


People also ask

Can a function in Python return a dictionary?

Any object, such as dictionary, can be the return value of a Python function.

What happens if you assign a new value to a dictionary using a key that already exists?

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.

Can you add new keys to a dictionary?

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.

Which method on a dictionary will return a value given a key?

The get() method returns the value for the specified key if the key is in the dictionary.


1 Answers

Sure, you can simply use dict(), for example:

old = {"a": 1}
new_one = dict(old, new_key=value)
#or
new_one = dict(old, {...})
like image 120
Sraw Avatar answered Sep 26 '22 01:09

Sraw