How do i turn a list into a dict? [duplicate] - python

This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Closed 8 months ago.
I'm making a Python(3) progam to read this text file:
firstval="myval"
secondval="myotherval"
and turn it into a dict.
I tried this:
lines = file.readlines().split("\n")
values = []
for line in lines:
values.append(line.split("="))
to turn the file into a list
How do i turn this:
values = ["firstval", "myval", "secondval", "myotherval"]
into this:
values = {
"firstval": "myval",
"secondval": "myotherval"
}

You can use dict() with zip():
dict(zip(values[::2], values[1::2]))
This outputs:
{'firstval': 'myval', 'secondval': 'myotherval'}

Related

Python string format template for selected parameters [duplicate]

This question already has answers here:
partial string formatting
(23 answers)
Closed 7 months ago.
I want to create a string template that only selected parameters gets value in each session.
For example:
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {fruit_name} very much"
s.format(fruits_num=fruits_num, fruit_name='apple')
s.format(fruits_num=fruits_num, fruit_name='orange')
I want to avoid the repeated assignment of fruits_num=fruits_num
In a pseduo code:
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {fruit_name} very much".format(fruits_num=fruits_num)
s.format(fruit_name='apple')
s.format(fruit_name='orange')
I this possible? Thanks.
You can double the { around fruits_name so that it will be literal, which will keep it until the next call to .format().
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {{fruit_name}} very much".format(fruits_num=fruits_num)
print(s.format(fruit_name='apple'))
print(s.format(fruit_name='orange'))

Dictionary Conversion [duplicate]

This question already has answers here:
How to reverse a dictionary that has repeated values
(7 answers)
Closed 1 year ago.
I got an python interview question:
#Dictionary
Convert
i = {"volvo":"car", "benz":"car", "yamaha":"bike", "hero":"bike"}
in to
output = {"car":["volvo", "benz"], "bike":["yamaha", "hero"]}
You can use the try/except process to reorder the dictionary.
i = {"volvo":"car", "benz":"car", "yamaha":"bike", "hero":"bike"}
output ={}
for k, it in i.items():
try:
output[it].append(k)
except KeyError:
output[it] = [k]
print(output)
Output:
{'car': ['volvo', 'benz'], 'bike': ['yamaha', 'hero']}

How to use a variable as a dictionary key? [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 3 years ago.
coming_monday = today + datetime.timedelta(days=-today.weekday(), weeks=1)
month = coming_monday.strftime("%B")
collection = db['empmain']
record = collection.find_one({'Availablity.<want to pass in the month variable here'})
format of the collection:
enter image description here
This example worked for me:
a = 1
b = 2
c = 3
mydict = {a : "a_", b : "b_", c : "c_"}
I've declard some variables with some values as above.
>>> mydict[1]
'a_'
>>> mydict[b]
'b_'
I was able to access values in the dictionary using both the variable names or the values.

How can I dynamically create a name of a variable in Python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I am having a function in python
def func(dataFrame,country,sex):
varible_name=dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
Now, for example, I call this function
func(dataFrame,'England','M')
I want that variable name be England_M instead of variable_name.
You can't do that in Python.
What you can do instead is store the results under a dictionary with key = England_M for instance.
In your case, you could do the following :
def func(dataFrame,country,sex):
tmp = dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
variable_name = "{c}_{s}".format(c=country, s=sex)
return dict(variable_name=tmp)
Now using it :
results = func(dataFrame, "England", "M")
print(results['England_M'])

custom order of a python list [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 8 years ago.
i'm using glob.glob() to get a list of files from a directory.
the result is this list. there is a way i can sort it using the int part of the filename?
['export_p-01.xml',
'export_p-02.xml',
'export_p-03.xml',
'export_p-04.xml',
'export_p-05.xml',
'export_p-06.xml',
'export_p-07.xml',
'export_p-08.xml',
'export_p-09.xml',
'export_p-10.xml',
'export_p-100.xml',
'export_p-101.xml',
'export_p-102.xml',
'export_p-103.xml',
'export_p-104.xml',
'export_p-105.xml',
'export_p-106.xml',
'export_p-107.xml',
'export_p-108.xml',
'export_p-109.xml',
'export_p-11.xml',
]
Here you go, with a custom lambda for using as key:
In [1]: l = ['export_p-01.xml', ...]
In [2]: sorted(l, key = lambda x: int(x.split(".")[0].split("-")[-1]))
Out[2]:
['export_p-01.xml',
'export_p-02.xml',
'export_p-03.xml',
'export_p-04.xml',
'export_p-05.xml',
'export_p-06.xml',
'export_p-07.xml',
'export_p-08.xml',
'export_p-09.xml',
'export_p-10.xml',
'export_p-11.xml',
'export_p-100.xml',
'export_p-101.xml',
'export_p-102.xml',
'export_p-103.xml',
'export_p-104.xml',
'export_p-105.xml',
'export_p-106.xml',
'export_p-107.xml',
'export_p-108.xml',
'export_p-109.xml']

Categories