Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Perl 6 have an equivalent to Python's update method on dictionary?

Tags:

raku

In Python, if I update the dict dictionary with another dict called u(use Perl as key), it will update the value:

>>> dict = {'Python':'2', 'Perl' : 5}
>>> u = {'Perl' : 6}
>>> dict.update(u)
>>> dict
{'Python': '2', 'Perl': 6}

but in Perl 6 :

> my %hash = 'Python' => 2, Perl => 5;
> my %u = Perl => 6
> %hash.append(%u)
{Perl => [5 6], Python => 2}

So, Does Perl 6 have an equivalent to Python's update method on dictionary?

like image 407
chenyf Avatar asked Nov 21 '17 07:11

chenyf


People also ask

What is the use of update function in python?

The update() method inserts the specified items to the dictionary. The specified items can be a dictionary, or an iterable object with key value pairs.


2 Answers

You can use the , operator to do the update:

my %u = Perl => 6;
my %hash = 'Python' => 2, Perl => 5;
%hash = %hash, %u;
say %hash;   # => {Perl => 6, Python => 2}

And of course you can shorten the updating line to

%hash ,= %u;
like image 100
timotimo Avatar answered Oct 25 '22 11:10

timotimo


In Perl 6, one option is to use a hash slice:

my %u = (Perl => 6);
%hash{%u.keys} = %u.values;

Result:

{Perl => 6, Python => 2}
like image 24
Håkon Hægland Avatar answered Oct 25 '22 11:10

Håkon Hægland