Reputation: 84
I have just encountered Perl code similar to the following:
my @keys = qw/ 1 2 3 /;
my @vals = qw/ a b c /;
my %hash;
@hash{@keys} = @vals;
This code populates an associative array given a list of keys and a list of values. For example, the above code creates the following data structure (expressed as JSON):
{
"1": "a",
"2": "b",
"3": "c"
}
How would one go about doing this in Python?
Upvotes: 1
Views: 74
Reputation: 103884
You can do:
>>> keys='123'
>>> vals='abc'
>>> dict(zip(keys,vals))
{'1': 'a', '3': 'c', '2': 'b'}
(Python note: strings are iterable, so list('abc')
is the rough equivalent of my @vals = qw/ a b c /;
in Perl)
Then if you want JSON:
>>> import json
>>> json.dumps(dict(zip(keys,vals)))
'{"1": "a", "3": "c", "2": "b"}'
Upvotes: 1
Reputation: 14619
That json is pretty much a polyglot with Python. Once you assign it to a name, though, it stops being a polyglot.
hf = {
"1": "a",
"2": "b",
"3": "c"
}
You can also iteratively align items into a dictionary.
letters = ('a', 'b', 'c', )
numbers = ('1', '2', '3', )
hf = { n : l for n, l in zip(numbers, letters) }
Upvotes: 1
Reputation: 236024
Like this:
import json
keys = [1, 2, 3]
vals = ['a', 'b', 'c']
hash = dict(zip(keys, vals))
json.dumps(hash)
=> '{"1": "a", "2": "b", "3": "c"}'
Upvotes: 1