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

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()))

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.

How to get the value from JSON key and update it accordingly? [duplicate]

This question already has answers here:
Edit the values in a list of dictionaries?
(4 answers)
Closed 1 year ago.
I have the following JSON, I want to be able to get the value for a certain key and update it accordingly.
So for example take a look at the key 'a' in the first JSON object, I want to be able to get its value '2' and then update the value for 'a' to whatever I want. It is important I can work with the value, incase I want to reformat date/time for example and update the key.
All help appreciated
x = "test" : [{
"a":"2",
"b":"12",
"c":"24",
"d":"223",
"e":"23",
},
{"a":"22",
"x":"24",
"c":"25",
"d":"21",
"e":"25",
},
{"a":"12",
"y":"23",
"c":"25",
"d":"23",
"e":"21",
}],
You could do this.
keyFor = 'a'
#get value
aVal = x['test'][0][keyFor]
#change value
aVal = int(aVal) + 2
#substitute in x
x['test'][0][keyFor] = aVal
print(x)

Dictionary converted to array in python [duplicate]

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))

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())

Looping through dict elements in python [duplicate]

This question already has answers here:
python: read json and loop dictionary
(2 answers)
Closed 6 years ago.
I have a piece of json which was converted to a dict using the json function.
From this:
{
"imageIds": [
{
"imageTag": "1.2",
"imageDigest": "sha256:8b67b1691b29e27a5ccbd6fea5c97c951a025ccd45b26d4c24567ca3c4c0f13b"
},
{
"imageTag": "1.0",
"imageDigest": "sha256:aa52a12bd6e516659452af5b9ed0fad8659f9e0cea6a986c6bfe02af388df189"
}
]
}
To this:
>>> print data
{u'imageIds': [{u'imageTag': u'1.2', u'imageDigest': u'sha256:8b67b1691b29e27a5ccbd6fea5c97c951a025ccd45b26d4c24567ca3c4c0f13b'}, {u'imageTag': u'1.0', u'imageDigest': u'sha256:aa52a12bd6e516659452af5b9ed0fad8659f9e0cea6a986c6bfe02af388df189'}]}
In this example the number of keys (imageIds) is fixed but there could be any amount of imageTags under imageIds.
What I'm trying to do is loop through the 'imageTag' elements to read the tag number and perform an operation. If i wanted to loop through the key it seems straightforward with something simple like:
for key in data:
print key, 'corresponds to', data[key]
However I'm uncertain on how I loop through the items under the key.
What I want to achieve is to print out:
1.2
1.0
Iterate over inner dict the same way you do for the outer one:
for key, value in data.iteritems():
#now value can be a dictionary as well
#for innerkey, innervalues in value[0].iteritems():
# print innerkey, innervalues
#in order to only print the elements that have imageTag as the key, simply do:
print value[0]['imageTag']

Categories