'How to Initialise and retrieve a mappings of mappings in solidity

Hi Solidity programmers!

I need to initialise a mapping of mapping:

mapping(string => mapping(string => uint8)) private _game_rule_strategy;

I simply want to know how to do it in solidity. In python, the same objective can be done like :

dictionary = {'Rock':{'Scissor':1, 'Paper':0}, 'Paper':{'Scissor':0, 'Rock': 1}}

To retrieve, i would write something like : dictionary['Paper']['Rock']. How do i achieve this in solidity?

Thanks!



Solution 1:[1]

You can take a cue from this smart contract code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract NestedMapping {
    mapping(string => mapping(string => uint8)) private _game_rule_strategy;

    function setNestedMapping(string memory _firstKey, string memory _secondKey, uint8 _value) public {
        _game_rule_strategy[_firstKey][_secondKey] = _value;
    }

    function getValueNestedMapping(string memory _firstKey, string memory _secondKey) external view returns(uint8) {
        return _game_rule_strategy[_firstKey][_secondKey];
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kerry99