CMS Development

jkupczak
Contributor

How do I create a copy or clone of a dict?

SOLVE

The documentation mentions the .copy() function as a solution, but I only get errors when attempting to use it.

 

https://developers.hubspot.com/docs/cms/hubl/functions#copy

1 Accepted solution
KBarnes_Breck
Solution
Member | Platinum Partner
Member | Platinum Partner

How do I create a copy or clone of a dict?

SOLVE

Hi @jkupczak 

 

A workaround I have found is to use the to and from json filters to create the copy.

 

{% set dict = {'a' : 1} %}
{% set copy_of_dict = dict|tojson|fromjson  %}
              
orig: {{dict}}
copy: {{copy_of_dict}}

After Append
{% do dict.put("b",2) %}
orig: {{dict}}
copy: {{copy_of_dict}}

 

Karla

View solution in original post

4 Replies 4
GRajput
Recognized Expert | Gold Partner
Recognized Expert | Gold Partner

How do I create a copy or clone of a dict?

SOLVE

Hi @jkupczak 

 

Sure, the documentation you provided mentions that you're getting errors while using the .copy() function. The reason you might be getting errors is because the .copy() method creates a shallow copy of the dictionary. This means that the new dictionary contains references to the same objects as the original dictionary. If you modify the copied dictionary, the changes will also be reflected in the original dictionary.

 

I hope this will help you out. Please mark it as Solution Accepted and upvote to help another Community member.
Thanks!




Gaurav Rajput
Director, MarTech( Growth Natives)

Book a meeting


0 Upvotes
KBarnes_Breck
Solution
Member | Platinum Partner
Member | Platinum Partner

How do I create a copy or clone of a dict?

SOLVE

Hi @jkupczak 

 

A workaround I have found is to use the to and from json filters to create the copy.

 

{% set dict = {'a' : 1} %}
{% set copy_of_dict = dict|tojson|fromjson  %}
              
orig: {{dict}}
copy: {{copy_of_dict}}

After Append
{% do dict.put("b",2) %}
orig: {{dict}}
copy: {{copy_of_dict}}

 

Karla

GiantFocal
Top Contributor | Gold Partner
Top Contributor | Gold Partner

How do I create a copy or clone of a dict?

SOLVE

Hi @jkupczak,

 

Could you provide more context about what you're trying to do?

And a screenshot of your codes would be helpful. 


Best regards,

Abraham Ernesto

Best regards,
Ernesto @ GiantFocal
Found this answer helpful?
Marking it as the solution helps both the community and me - thanks in advance!
0 Upvotes
jkupczak
Contributor

How do I create a copy or clone of a dict?

SOLVE

I want to create a dict, and then create a copy/clone of that dict.

 

 

{% set dict = { "a": 1 } %}
{% set copy_of_dict = dict %}

 

 

But this code doesn't create two unique dicts, it just assigns the first dict to another variable. And so if I were to append data to either `dict` or `copy_of_dict`, they would both be updated which I do not want.

0 Upvotes