how to add key and turn dictonary key to value? - python

I have dictionary like this:
a = {"RAM": ["25GB", "256GB"], "Storage": ["25GB"]}
and is there any possible way to make dictionary like this?
wanted_dict = [{"title":"RAM", "items":["25GB", "256GB"]}, {"title":"Storage", "items":["25GB"]}]
i tried to do with for loop but with no result.
any advices?

a = {"RAM": ["25GB", "256GB"], "Storage": ["25GB"]}
list_a = [{'title': key, 'items': values} for key, values in a.items()]

From what I can understand you want to convert the value of a to the value of wanted_dict without hard-coding it. If so, here's the code:
a = {"RAM": ["25GB", "256GB"], "Storage": ["25GB"]}
b = []
for key in a:
entry = {"title": key, "items": a[key]}
b.append(entry)
print(b)
So then you could do:
a = b

Related

python get dictionary values list as list if key match

I have the following list and dictionary:
match_keys = ['61df50b6-3b50-4f22-a175-404089b2ec4f']
locations = {
'2c50b449-416e-456a-bde6-c469698c5f7': ['422fe2d0-b10f-446d-ac3c-f75e5a3ff138'],
'61df50b6-3b50-4f22-a175-404089b2ec4f': [
'7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce'
]
}
If I want to search 'locations' for keys that match in the match_keys list and extract their values, to get something like this...
['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']
...what would be the best way?
You can iterate over match_keys and use dict.get to get the values under each key:
out = [v for key in match_keys if key in locations for v in locations[key]]
Output:
['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']
for key, value in locations.items():
if key == match_keys[0]:
print(value)
Iterate over keys and get value by [].
res = []
for key in matched_keys:
res.append(matched_keys[key])
or if you dont want list of lists you can use extend()
res = []
for key in matched_keys:
res.extend(matched_keys[key])

get maximum valued dictionary from list of dictionaries in python

I have this list.
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
I want output as:
[ {"rp":1,"vi":200},{"rp":2,"vi":300},{"rp":3,"vi":120}]
Can anyone help??
You can build a temporary dictionary using the 'rp' values as keys and feeding the data in order of 'vi' value to retain the highest 'vi' value for each unique 'rp' key. Then convert the values of that temporary dictionary into a list of dictionaries:
R = [*{d["rp"]:d for d in sorted(dict_list,key=lambda d:d["vi"])}.values()]
print(R)
[{'rp': 2, 'vi': 300}, {'rp': 1, 'vi': 200}, {'rp': 3, 'vi': 120}]
One solution could be to create a dictionary with key as the rp value and value as the maximum vi value.
Use the created dictionary to create the required list
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
res = dict()
for elt in dict_list:
res[elt["rp"]] = max(res.get(elt["rp"], 0), elt["vi"]) # overwrite with max for matching keys
dict_list = [{"rp": key, "vi": value} for key, value in res.items()]
print(dict_list)
I am not sure if this is the most elegant way to do it but I hope it helps.
you can try to use pandas for something like this:
import pandas as pd
dict_list = [{"rp":1,"vi":100},{"rp":2,"vi":70},{"rp":1,"vi":200},
{"rp":1,"vi":150},{"rp":2,"vi":300},{"rp":3, "vi":120 }]
full = pd.DataFrame(dict_list)
rp_list = pd.Series(full['rp']).unique()
new= []
for rp in rp_list:
values = full.loc[full['rp'] == rp]
max_value = values["vi"].max()
new.append({'rp':rp,'vi':max_value})
print (new)

How do I create a list inside python dictionary having key and key variable?

I have an empty dictionary. I add key and key variable to that dictionary. How do I create an empty list having key and key variable?
result = {}
result['key'] = 20
print(result)= {'key': 20}
result['key'] = []
result2 = {}
result['key'].append(result2)
Expected result : {'key':20 : [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}
But it comes like,
{'key': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}]
Looks like you need.
result = {}
result['key'] = {20: []}
print(result) # --> {'key': {20: []}}
result2 = {}
result['key'][20].append(result2)
print(result)
As far as I understand your question, you do not necessarily want to save the value "20" with the key "key", but rather use "20" as the key. In order to achieve that, your code should look like the following (careful, this basically spells out every step):
# save an empty list using the key int(20)
# define the key and an empty dictionary
my_key = 20
result = {}
# use the key variable as key for the dictionary and create an empty list there
result[my_key] = []
# now add the other result dictionary to this list
result2 = {
#... some entries
}
result[my_key].append(result2)
# ... some more code
This finally results in a dictionary in this form:
{20 : [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}]}
However, this is only my interpretation of your issue. If I got something wrong, just ping me up.

Pythonic Way To Replace Dict Keys and/or Values

I'm looking for an 'efficient' way to iterate through a dictionary, and replace any key or value that starts with the term 'var'.
For example, if I have this:
data = {
"user_id": "{{var_user_id}}",
"name": "bob",
"{{var_key_name}}": 4
}
and I have this dict of variable values:
variables = {
"user_id": 10,
"key_name": "orders_count"
}
Then I'd like my final data dict to look like this:
data = {
"user_id": 10,
"name": "bob",
"orders_count": 4
}
Since you're treating it like a text template language (and if you are, then why not make it string.format(**variable) compatible syntax?) use text replacement:
import ast
import re
text = re.sub('{{var_(.*?)}}', lambda m: variables[m.groups()[0]], str(data))
data2 = ast.literal_eval(text)
print(data2)
In straight-forward way:
result = {}
for k,v in data.items():
if '{{var_' in k: # if `{{var..}}` placeholder is in key
result[variables[k[6:-2]]] = v
elif '{{var_' in v: # if `{{var..}}` placeholder is in value
result[k] = variables[v[6:-2]]
else:
result[k] = v
print(result)
The output:
{'user_id': 10, 'orders_count': 4, 'name': 'bob'}
This is a pretty manual algorithm, but here goes:
for key, value in data.iteritems():
if "var" in str(key):
#iterate through "variables" to find the match
elif "var" in str(value):
#iterate through "variables" to find the match
#populate "data" with the key value pair
This will work, but it's kind of messy if you can't guarantee uniqueness, especially in the case where a key needs to be replaced.

How do I find an item in an array of dictionaries?

Suppose I have this:
list = [ { 'p1':'v1' } ,{ 'p2':'v2' } ,{ 'p3':'v3' } ]
I need to find p2 and get its value.
You can try the following ... That will return all the values equivilant to the givenKey in all dictionaries.
ans = [d[key] for d in list if d.has_key(key)]
If this is what your actual code looks like (each key is unique), you should just use one dictionary:
things = { 'p1':'v1', 'p2':'v2', 'p3':'v3' }
do_something(things['p2'])
You can convert a list of dictionaries to one dictionary by merging them with update (but this will overwrite duplicate keys):
dict = {}
for item in list:
dict.update(item)
do_something(dict['p2'])
If that's not possible, you'll need to just loop through them:
for item in list:
if 'p2' in item:
do_something(item['p2'])
If you expect multiple results, you can also build up a list:
p2s = []
for item in list:
if 'p2' in item:
p2s.append(item['p2'])
Also, I wouldn't recommend actually naming any variables dict or list, since that will cause problems with the built-in dict() and list() functions.
These shouldn't be stored in a list to begin with, they should be stored in a dictionary. Since they're stored in a list, though, you can either search them as they are:
lst = [ { 'p1':'v1' } ,{ 'p2':'v2' } ,{ 'p3':'v3' } ]
p2 = next(d["p2"] for d in lst if "p2" in d)
Or turn them into a dictionary:
dct = {}
any(dct.update(d) for d in lst)
p2 = dct["p2"]
You can also use this one-liner:
filter(lambda x: 'p2' in x, list)[0]['p2']
if you have more than one 'p2', this will pick out the first; if you have none, it will raise IndexError.
for d in list:
if d.has_key("p2"):
return d['p2']
If it's a oneoff lookup, you can do something like this
>>> [i['p2'] for i in my_list if 'p2' in i]
['v2']
If you need to look up multiple keys, you should consider converting the list to something that can do key lookups in constant time (such as a dict)
>>> my_list = [ { 'p1':'v1' } ,{ 'p2':'v2' } ,{ 'p3':'v3' } ]
>>> my_dict = dict(i.popitem() for i in my_list)
>>> my_dict['p2']
'v2'
Start by flattening the list of dictionaries out to a dictionary, then you can index it by key and get the value:
{k:v for x in list for k,v in x.iteritems()}['p2']

Categories