Search code examples
pythonsnakemake

snakemake: correct syntax for accessing dictionary values


Here's an example of what I am trying to do:

mydictionary={
'apple': 'crunchy fruit',
'banana': 'mushy and yellow'
}

rule all:
    input:
        expand('{key}.txt', key=mydictionary.keys())

rule test:
    output: temp('{f}.txt')
    shell:
        """
        echo {mydictionary[wildcards.f]} > {output}
        cat {output}
        """

For some reason, I am not able to access the dictionary contents. I tried using double-curly brackets, but the content of the text files becomes literal {mydictionary[wildcards.f]} (while I want the content of the corresponding entry in the dictionary).


Solution

  • I'm pretty sure the bracket markup can only replace variables with string representations of their values, but does not support any code evaluation within the brackets. That is, {mydictionary[wildcards.f]} will try to look up a variable literally named "mydictionary[wildcards.f]". Likewise, {mydictionary}[{wildcards.f}] will just paste the string values together. So, I don't think you can do what you want within the shell section alone. Instead, you can accomplish what you want in the params section:

    rule test:
        output: temp('{f}.txt')
        params:
            value=lambda wcs: mydictionary[wcs.f]
        shell:
            """
            echo '{params.value}' > {output}
            cat {output}
            """