python dict in formatted string [duplicate] - python

This question already has answers here:
How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?
(23 answers)
Closed 7 years ago.
I want to write a python dictionary in a string. The values of the items should be give by the formatted string.
I expected the following to work, but it doesnt because the first '{' used to define the dict is interpreted as a formated field
In: "{'key_1': '{value}'}".format(**{'value': 'test'})
the following works fine, but doesn't return the expected dict:
In: "'key_1': '{value}'".format(**{'value': 'test'})
Out: "'key_1': 'test'"
one way to overcome the problem is by using list brakets and replace them later by the dict brakets:
In: "['key_1': '{value}']".format(**{'value': 'test'}).replace('[', '{').replace(']', '}')
Out: "{'key_1': 'test'}"
How to write this in a better way?

Use double {{and }}:
"{{'key_1': '{value}'}}".format(**{'value': 'test'})

Related

Is there a way to write single backslash within lists? [duplicate]

This question already has an answer here:
Why does printing a tuple (list, dict, etc.) in Python double the backslashes?
(1 answer)
Closed 1 year ago.
enter image description here
is there a way to print single backslash within list?
Regarding the first version of your question, I wrote this:
First, this expression x='\' isn't right in Python in python. you should rather puth it this way: x='\\', since back slash is a special character in python.
Second, try this:
l=['\\'] print(l)
This will print: ['\\']
But when you execute this: print(l[0]), it renders this '\'. So basically, this ['\\'] is the way to print a backslash within a list.

How to print string variable as f string in python [duplicate]

This question already has answers here:
How do I convert a string into an f-string?
(3 answers)
Closed 2 years ago.
i want to print my user variable from my python script to a html document and this is the way I have to do this.
How do i go about doing it?
my_python.py
user = "myname"
with open("../../html/forms/output.html") as output:
print(output.readlines())
output.html
<h1>{user}</h1>
EXPECTED OUTPUT :
<h1>myname</h1>
ACTUAL OUTPUT :
<h1>{user}</h1>
f-string is a syntax and not an object, and as a result - You can't convert a string to f-string.
If you know the names of the "variables" inside your template file, you can do:
output.read().format(user=user)

String format: getting u'' inside the final string [duplicate]

This question already has answers here:
Removing u in list
(8 answers)
Closed 3 years ago.
I have a list of id's and I am trying the following below:
final = "ids: {}".format(tuple(id_list))
For some reason I am getting the following:
"ids: (u'213231231', u'weqewqqwe')
Could anyone help out on why the u is coming inside my final string. When I am trying the same in another environment, I get the output without the u''. Any specific reason for this?
Actually it is unicode strings in python
for literal value of string you can fist map with str
>>> final = "ids: {}".format(tuple(map(str, id_list)))
>>> final
"ids: ('213231231', 'weqewqqwe')

Duplicate Key in dictionary in python [duplicate]

This question already has answers here:
How can one make a dictionary with duplicate keys in Python?
(9 answers)
Python JSON parse duplicate records
(1 answer)
Closed 3 years ago.
Python: 3.7.3
I have a string which needs to be converted to dictionary.
So, I have achieved it using ast.literal_eval method.
my_string = "{'ReceiptMessageId':'foo','ReceiptMessageId':'boo','ReceiptMessageName':'zoo'}"
import ast
my_dict = ast.literal_eval(my_string)
But issue here is, string (my_string) has same key with different values and converted dictionary replaces with lastly received value.
Expected:
{'ReceiptMessageId': ['foo','boo'], 'ReceiptMessageName': 'zoo'}
Actual:
{'ReceiptMessageId': 'boo', 'ReceiptMessageName': 'zoo'}
After googling a lot, I found this can be achieved using defaultdict from collections but in my case, duplicates are already ignored while converting into dict. Can someone give me an idea as to how to go about it?

Convert string of list to python list [duplicate]

This question already has answers here:
Converting a string to a tuple in python
(3 answers)
Closed 8 years ago.
I downloaded a csv table from a database using SQL. One of the fields has values like so:
'[0.1234,0.0,0.0]'
I want to convert this string to a python list to get the first value. I only know how to convert strings to ints and floats... is there any way to de-string this object? The table I got from SQL is from a web-based viewer, I'm not getting it from my command line.
You could take the substring from index 1 to index -1 and then split it using the comma as a delimiter. In python
array = variable[1:-1].split(',')
should work.
If you're sure it is always valid list syntax, you could use"
myList = eval('[0.1234,0.0,0.0]')
Or if the value itself has quotes ' in it, you can slice those off
value = "'[0.1234,0.0,0.0]'"
myList = eval(value[1:-1])
Then to get the first value you just
myList[0]

Categories

Resources