Home > Mobile >  Create a dictionary with a single line loop. [python]
Create a dictionary with a single line loop. [python]

Time:11-15

Hi I wanted to know if it was possible to code this function in a shorter way. In one line ?

I want to create a dictionary with a single line loop by inserting the two variables with the function "eval()".

def create_dictionnary(file):
    with open(file, encoding='utf-8') as f_o:
        dictionnary = {}
        for line in file:
            a, b = eval(line)
            dictionnary[a] = b
        return dictionnary

I want to do something like this but the only but is that I use a,b = eval()...

def create_dictionnary(file):
    with open(file, encoding='utf-8') as f_o:
        return {a:b, a,b = eval(line) for line in f_o}

If anyone can help me find a solution that would be great.

I tried to generate this function in one line but I can't find a way to do it.

CodePudding user response:

It's not recommended to use eval, because the input string may be a dangerous experssion. ast.literal_eval is recommened.

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

But if you do need, you can do this,

dict(eval(line) for line in f_o)

Example:

f_o = [ "(1, 2)", "('a', 'b')" ]
dict(eval(line) for line in f_o)
# {1: 2, 'a': 'b'}

If you use ast.literal_eval, here is another example.

import ast
dict(ast.literal_eval(line) for line in f_o)
# {1: 2, 'a': 'b'}

CodePudding user response:

First of all, a big thank to you ILS.

Secondly, I found the solution with your help!

so I had to split with

{eval(line)[0]:eval(line)[1] for line in f_o}

So here's my solution :

def create_dictionnary(file):
    with open(file, encoding='utf-8') as f_o:
        return {eval(line)[0]: eval(line)[1] for line in f_o}
  • Related