A line like "a=1 b=2 c=3" . It is necessary to read the value of the variables а,b,c in these variables. The problem is that these values can be mixed up (Not a,b,c , but b,a,c ). It is advisable to save all this in the dictionary, but it will come down in variables
- Related question: Creating dictionary from python (somewhat more complicated case) - jfs
|
3 answers
Here he writes in the dictionary with the keys 'a', 'b' and 'c' and the corresponding values:
d = {i.split('=')[0]: int(i.split('=')[1]) for i in input().split(' ')} print(d) Or like this:
d = {} for i in input().split(' '): spl = i.split('=') d[spl[0]] = int(spl[1]) print(d) - can be simplified to:
dict(kv.split('=') for kv in "a=1 b=2 c=3".split())if you do not need to convert toint. And if necessary, in order not to callsplit('=')twicesplit('='), you can use the hack:{k: int(v) for kv in s.split() for k, v in [kv.split('=')]}. Use:key, value = pair.split('=')$d[key] = int(value)instead ofspl = i.split('=')$d[spl[0]] = int(spl[1])- jfs
|
You can use ast.literal_eval () and re.findall () :
import re import ast s = 'a=1 b="2" c=3.123 d=[1, 2, 3] e={"Key1":"Val1", "Key2":"Val2"} f=0' print('исходная строка') print(s) # избавляемся от пробелов после запятой s = re.sub(r',\s+', ',', s) print('строка без лишних пробелов') print(s) d = ast.literal_eval( '{' + ','.join(['"{0[0]}":{0[1]}'.format(t) for t in re.findall(r'([^\s]*)=([^\s]*)', s)]) + '}' ) print('результат') print(d) Conclusion (I formatted the output slightly, for beauty):
исходная строка a=1 b="2" c=3.123 d=[1, 2, 3] e={"Key1":"Val1", "Key2":"Val2"} f=0 строка без лишних пробелов a=1 b="2" c=3.123 d=[1,2,3] e={"Key1":"Val1","Key2":"Val2"} f=0 результат {'a': 1, 'b': '2', 'c': 3.123, 'd': [1, 2, 3], 'e': {'Key1': 'Val1', 'Key2': 'Val2'}, 'f': 0} The advantage of this method is that it supports almost any built-in variable types:
- The question does not require the support of arbitrary Python-constants and the code in the answer and so it breaks down on the simplest input
'a=" "'. In general, such a ballet should be avoided: string -> objects -> string -> object (avoid jumping back and forth between a serialized view and deserialized unnecessarily ( see the link at the end of the answer ). - jfs - oneHere is a parser that supports lists and dictionaries, does not limit nesting and supports arbitrary string values. Without the recursion part, it is a simple automaton . - jfs
- @jfs, a very cool parser in my opinion. I think it is worth making it as a separate question + answer - surely it can be useful to many ... - MaxU
- onethis parser is not there and not here: it began its life as a finite state machine (what is shown in the picture generated using ragel is shown) to recognize the input in the answer, but on the way we also wanted to support nested structures. The result was something resembling a method of recursive descent ( LL (1) -language ) ... - jfs
- one... If we immediately ask ourselves to maintain arbitrary json (for definiteness) values, then the parser can be generated using grako (or another generator of parsers, which are many). Here is how the grammar looks, which it recognizes. - jfs
|
globals().update(eval('dict(%s)' % "a=1 b=2 c=3".replace(' ', ','))) print(a, b, c) - Add a detailed description of the solution or code to your answer so that users can more quickly understand your answer. - Yuri
- horrors: and
eval()andglobals()manipulation. If you want to get variables, you canexec("a=1 b=2 c=3".replace(' ', ';')). If the dictionary:d={}; exec("a=1 b=2 c=3".replace(' ', ';'), {}, d)d={}; exec("a=1 b=2 c=3".replace(' ', ';'), {}, d)Bothevalandexecshould be avoided - there are less explosive alternatives - jfs
|