Summary of Hash (Dictionary) operation support for Ruby and Python

Overview

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).

Prerequisites

Reference information

Method

Initialization

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}

Extracting elements

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]
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']

Generated from an array

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}

key, value map

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 = {'a': 1, 'b': 2, 'c': 3}
'a' in d                      #=> True
'd' in d                      #=> False

merge

h1 = {"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}

Setting the default value

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}
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})

When creating an index of an array

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

Summary of Hash (Dictionary) operation support for Ruby and Python
Correspondence summary of array operation of ruby and python
[python] Summary of how to retrieve lists and dictionary elements
Summary of Python indexes and slices
I compared the speed of Hash with Topaz, Ruby and Python
Summary of various for statements in Python
Summary of useful techniques for Python Scrapy
[Python] Dictionary (hash)
Instant method grammar for Python and Ruby (studying)
Summary of the differences between PHP and Python
Basic operation list of Python3 list, tuple, dictionary, set
Installation of Python3 and Flask [Environment construction summary]
Summary of frequently used Python arrays (for myself)
Code for checking the operation of Python Matplotlib
I / O related summary of python and fortran
About shallow and deep copies of Python / Ruby
Comparison of Python and Ruby (Environment / Grammar / Literal)
Basic operation of Python Pandas Series and Dataframe (1)
[Python] Operation of enumerate
Ruby, Python and map
Python and Ruby split
Python directory operation summary
Summary of Python arguments
List of Python libraries for data scientists and data engineers
Summary of Python sort (list, dictionary type, Series, DataFrame)
Python netCDF4 read speed and nesting of for statements
Python --Explanation and usage summary of the top 24 packages
[Python] Type Error: Summary of error causes and remedies for'None Type'
Summary of python environment settings for myself [mac] [ubuntu]
Difference between Ruby and Python in terms of variables
Summary of tools for operating Windows GUI with Python
Summary of pre-processing practices for Python beginners (Pandas dataframe)
Support for Python 2.7 runtime on AWS Lambda (as of 2020.1)
English-English dictionary confrontation for Python and AI related English
Summary of date processing in Python (datetime and dateutil)
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
Version control of Node, Ruby and Python with anyenv
Build API server for checking the operation of front implementation with python3 and Flask
About Fabric's support for Python 3
Python list, for statement, dictionary
Summary of python file operations
Python on Ruby and angry Ruby on Python
Check the operation of Python for .NET in each environment
Applied practice of try/except and dictionary editing and retrieval in Python
Simulation of late damages for child support delinquency with python
Python and ruby slice memo
Standard input / summary / python, ruby
[Python] Summary of how to use split and join functions
Ruby and Python syntax ~ branch ~
Python: Create a dictionary from a list of keys and values
Source installation and installation of Python
Summary of Differences Between Ruby on Rails and Django ~ Basics ~
Building a Docker working environment for R and Python 2: Japanese support
Build and test a CI environment for multiple versions of Python
A brief summary of Graphviz in python (explained only for mac)
Summary of recommended APIs for artificial intelligence, machine learning, and AI
Solving with Ruby, Python and numpy AtCoder ABC054 B Matrix operation
Summary of differences between Python and PHP (comparison table of main items)
[For beginners] Summary of suffering from kaggle's EDA and its struggle
Environment construction of python and opencv
Difference between Ruby and Python split