A summary of typical operations of Array in Ruby and Hash (Dictionary) in Python.
This is an article for Rubyist (Pythonista) who has just started learning Python (Ruby).
h = {"a" => 1, "b" => 2, "c" => 3}
h2 = {a: 1, b: 2, c: 3} #When symbol is key
d = {'a': 1, 'b': 2, 'c': 3}
h['c'] #=> 3
h['d'] #=> nil
d['c'] #=> 3
d['d'] #=>Exception KeyError occurs
size
h.size #=> 3
len( d ) #=> 3
each
Loop around the element
h.each do |key,val|
puts key,val
end
for k,v in d.items():
print(k,v)
keys, values
Get a list of key and value
h.keys #=> ["a", "b", "c"]
h.values #=> [1, 2, 3]
list ()
if you want a list.keys = d.keys() #=> dict_keys(['b', 'a', 'c'])
values = d.values() #=> dict_values([2, 1, 3])
d['d'] = 4
keys #=> dict_keys(['b', 'd', 'a', 'c'])
values #=> dict_values([2, 4, 1, 3])
list(keys) #=> ['b', 'd', 'a', 'c']
a = [1,2,3,4]
a.map {|x| [x,x+3] }.to_h #=> {1=>4, 2=>5, 3=>6, 4=>7}
a = [1,2,3,4]
{ i:i+3 for i in a } #=> {1: 4, 2: 5, 3: 6, 4: 7}
Hash []
h = {"a" => 1, "b" => 2, "c" => 3}
h.map {|k,v| [k.upcase, -v] } #=> [["A", -1], ["B", -2], ["C", -3]]
h.map {|k,v| [k.upcase, -v] }.to_h #=> {"A"=>-1, "B"=>-2, "C"=>-3}
d = {'a': 1, 'b': 2, 'c': 3}
{ k.upper():-v for k,v in d.items() } #=> {'A': -1, 'B': -2, 'C': -3}
has_key?
h = {"a" => 1, "b" => 2, "c" => 3}
h.has_key?("a") #=> true
h.has_key?("d") #=> false
d.has_key ('a')
up to python2.d = {'a': 1, 'b': 2, 'c': 3}
'a' in d #=> True
'd' in d #=> False
merge
Hash # merge
. Non-destructive method. The destructive method is merge!
--If there is the same key, the value of the argument takes precedence by default. Can be specified by passing a block
- https://docs.ruby-lang.org/ja/latest/method/Hash/i/merge.htmlh1 = {"a" => 1, "b" => 2, "c" => 3}
h2 = {"d" => 4, "e" => 5, "f" => 6}
h1.merge(h2)
# => {"a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5, "f"=>6}
d1 = {"a": 1, "b": 2, "c": 3}
d2 = {"d": 4, "e": 5, "f": 6}
d1.update(d2)
d1
#=> {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
delete
h = {"a" => 1, "b" => 2, "c" => 3}
h.delete('a') #=> 1
h #=> {"b"=>2, "c"=>3}
d = {"a": 1, "b": 2, "c": 3}
d.pop('a') #=> 1
d #=> {'b': 2, 'c': 3}
Case of using an associative array when taking a histogram
chars = ["a", "b", "b", "c", "c", "c"]
h = Hash.new(0)
chars.each {|c| h[c] += 1 } #Counting the number of characters
h #=> {"a"=>1, "b"=>2, "c"=>3}
default_dict
chars = ["a", "b", "b", "c", "c", "c"]
d = {}
for c in chars:
d[c] = d.get(c,0) + 1 #Get if there is a value, return 0 if not
d #=> {'a': 1, 'b': 2, 'c': 3}
from collections import defaultdict
chars = ["a", "b", "b", "c", "c", "c"]
d = defaultdict( lambda: 0 )
for c in chars:
d[c] += 1
d
# => defaultdict(<function __main__.<lambda>>, {'a': 1, 'b': 2, 'c': 3})
Hash.new ([])
is a bug
words = ["a1", "b1", "b2", "c1", "c2", "c3"]
h = Hash.new {|hash,key| hash[key] = [] }
words.each {|w| h[ w[0] ] << w }
h
# => {"a"=>["a1"], "b"=>["b1", "b2"], "c"=>["c1", "c2", "c3"]}
words = ["a1", "b1", "b2", "c1", "c2", "c3"]
d = defaultdict( list )
for w in words:
key = w[0]
d[key].append(w)
d
#=> defaultdict(list, {'a': ['a1'], 'b': ['b1', 'b2'], 'c': ['c1', 'c2', 'c3']})
Recommended Posts