Dictionary converted to array in python [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
d={'a0': [['5021', '5031'], ['4994', '4991', '5042'],
['4992', '4995', '5021', '4994'], ['5037', '5038']],
'a24': [['5009', '5014'], ['5009', '5014'], ['4993', '4998', '5030', '4991']]
}
I have the above dict in python.
I need to make list with the name of it being the names of keys in the dict.
The list with the name of the key should have the items as its corresponding values in dict.
The output should be:
a0=[['5021', '5031'], ['4994', '4991', '5042'],
['4992', '4995', '5021', '4994'], ['5037', '5038']]
a24=[['5009', '5014'], ['5009', '5014'], ['4993', '4998', '5030', '4991']]
Any help is appreciated.

First, rethink if this is really necessary. Dynamically creating variables is confusing and does not occur often. It would be better to avoid this.
However, you can do it like this:
for name, val in d.items():
exec("{}={}".format(name,val))

for key, item in d.items():
print(str(key) + "=" + str(item))

Related

Complicated list comprehension [duplicate]

This question already has answers here:
Check if a given key already exists in a dictionary
(16 answers)
Closed 6 months ago.
Im trying to build a list through list comprehension in python.
What I have so far, and it works:
modified_list = [
{id: metadata}
for id, metadata in new_resource_map.items()
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"]
]
My list called: modified_list
Every item in it is dictionary {id: metadata}
I want to add one more thing and it will look like that:
modified_list = [
{id: metadata}
for id, metadata in new_resource_map.items()
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"] **or
metadata["infer_tags"] != old_resource_map[id]["infer_tags"]**
]
The problem is what the last part:
or metadata["infer_tags"] != old_resource_map[id]["infer_tags"]
The problem is not all of the files have that field ("infer_tags").
I wanna do this last thing only after I check if this field is existing.
Is anyone know to do that?
as Mechanic Pig suggests:
if id not in old_resource_map or metadata["lastModified"] != old_resource_map[id]["lastModified"] or
metadata.get("infer_tags", np.nan) != old_resource_map[id].get("infer_tags", np.nan)
Note that the default values used in the get() calls must not be valid values for infer_tags fields for this to be reliable.

Create Variable Name When Defining A Function [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am working in Python trying to write a function using a list of variables.
Here is the data I am working with:
material_list=['leather', 'canvas', 'nylon']
def materialz(MAT):
MAT=support.loc[(material==MAT)].sum()
for i in enumerate(material_list):
materialz(i)
What I am looking for is to pass in each of the items in the list to the function to produce global variables.
leather=
canvas=
nylon=
Any help would be appreciated!
You could create a dictionary and dynamically assign the key-value pairs there. Such as:
material_list=['leather', 'canvas', 'nylon']
material_dict={}
for i in enumerate(material_list):
material_dict[i]=value #Where i would be the key and value the value in the key-value pair
you can use exec
var = 'hello'
output = hello
exec('var = "world"')
print(var)
output = world

python how to sort a variable like {'a b': c, 'd e':f ....} [duplicate]

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 2 years ago.
I have a variable.
Score = {}
After some calculation, the value of Score is :
{
'449 22876': 0.7491997,
'3655 6388': 0.99840045,
'2530 14648': 0.9219989,
'19957 832': 0.9806836,
'2741 23293': 0.64072967,
'22324 7525': 0.986661,
'9090 3811': 0.90206504,
'10588 5352': 0.8018138,
'18231 7515': 0.9991332,
'17807 14648': 0.9131582
.....
}
I want to sort it by the third value(e.g. 0.7491997).
I only want to get the top 100 high score.
How can I do?
if you want to sort the dictionary by the values of the dictionary (which is what I am getting from your question) you could do it with this lambda function:
sorted_dict = sorted(score.items(), key=lambda x: x[1])

How to get a random element from a python dictionary? [duplicate]

This question already has answers here:
How to get a random value from dictionary?
(19 answers)
Closed 3 years ago.
I want to get a value "element":"value" from a dictionary in python.
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
random.choice(country)
It returns me the following :
File "C:\Users\${username}\AppData\Local\Programs\Python\Python37-32\lib\random.py", line 262, in choice
return seq[i]
KeyError: 10
My aim, is to select a random value and be left with 1 Country - City left in the dictionary.
This does not answer my question : How to get a random value from dictionary in python
You can use the items method to get the pairs, then transform it to a list that supports indexing:
random.choice(list(country.items()))
i think you can implement in following way
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
keys = list(country.keys())
random_key = keys[random.randint(0, len(keys)-1)]
print(country[random_key])
You can make a random.choice from the keys() of the dict for instance.
You could print the values or make a new dict with just that entry:
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
k = random.choice(list(country.keys()))
print(k, country[k])
print({k:country[k]})
First of all, there's no order in a dictionary. The only list can be used for random.sample.
So change your code to random.choice(list(country.items()))

Call Dictionary With Randomly Chosen Value as Name - TypeError [duplicate]

This question already has answers here:
Access to value of variable with dynamic name
(3 answers)
Closed 6 years ago.
I am using a function that assigns a variable to equal the value of a randomly chosen key. Here the type is string and print works.
def explore():
import random
random_key = random.choice(explore_items.keys())
found_item = explore_items[random_key]
print type(found_item)
print found_item
Then, I want to use the variable name 'found_item' to call a dictionary of the same name, eg:
print found_item['key_1']
But I get the error, "TypeError: string indices must be integers, not str"
How would I use a string to call a previously defined dictionary that shares the same name?
You can use a variable via its name as string using exec:
dic1 = {'k': 'dic2'}
dic2 = {'key_1': 'value'}
exec('print ' + dic1['k'] + "['key_1']")
Short answer: I don't think you can.
However, if the dictionary explore_items uses the dicts in questions as its keys, this should work.
ETA to clarify:
explore_items = {{dict1}: a, {dict2}:b, {dict3}:c}
random_key= random.choice(explore_items.keys())

Categories