I'm using python 3.3
I have a dictionary
dict = {'a': (3,1), 'b': (1,2), 'c': (1,1)}
i'm trying to generate one item at a time
when I write item I mean
item1 = 'a': (3,1)
item2 = 'b': (1,2)
etc'
i have tried:
for key, value in dict.items():
temp = [key, value]
yield temp
or
for item in dict:
yield dict[item],item
but both don't generate what I want.
any help will be greatly appreciated
Thanks!
def my_generator(d):
for key, value in d.items():
yield {key: value}
d = {'a': (3,1), 'b': (1,2), 'c': (1,1)}
for subdict in my_generator(d):
print subdict
This would yield:
{'a': (3,1)}
{'b': (1,2)}
{'c': (1,1)}
Related
I have the following list of dicts:
lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]
I want to filter the list of dicts (in my case it's a list of thousands or even more dicts, with different keys with some overlap) to be a list containing all the dicts that have keys: ["a", "b"]. I want to filter each dict only to these a and b keys, and if they don't exist, don't include the dictionary in the final list. I am using:
[{"a": d.get("a"), "b": d.get("b")} for d in lst]
Please advise for an elegant way to solve it.
The dictionary keys-view is set-like, so it supports subset comparisons by using <= operator:
>>> keys = set("ab")
>>> [{k: d[k] for k in keys} for d in lst if keys <= d.keys()]
[{'a': 1, 'b': 2}, {'a': 1, 'b': 2}]
I have figured it out and here is my alternative:
lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]
keys = set("ab")
[i for i in [{k: d.get(k) for k in keys if k in d} for d in lst] if i]
Gives the desired answer:
[{'b': 2, 'a': 1}, {'b': 2, 'a': 1}, {'a': 1}]
I have a list of the dictionary as follows:
[{"A":5,"B":10},
{"A":6,"B":13},
{"A":10,"B":5}]
I want to this list in decending order on the value of B. The output should look like this:
[{"A":6,"B":13},
{"A":5,"B":10},
{"A":10,"B":5}]
How to do that?
You can sort lists by the results of applying a function to each element: https://docs.python.org/3.9/library/functions.html#sorted
>>> data = [{"A":5,"B":10},
... {"A":6,"B":13},
... {"A":10,"B":5}]
>>> sorted(data, key=lambda dct: dct["B"], reverse=True)
[{'A': 6, 'B': 13}, {'A': 5, 'B': 10}, {'A': 10, 'B': 5}]
mylist = [{'a': 'banana'}, {'a': 'orange'}, {'b': 'apple'}, {'c': 'grapes'}, {'b': 'banana'}, {'c': 'apple'}]
I want to change this into a dictionary with same keys to have list of value like so:
mylist = [{'a': 'banana', 'orange'}, {'b': 'apple', 'banana'}, {'c': 'grape' 'apple'}]
My code:-
mydict_ = defaultdict(list)
for x in mylist:
for k, v in x.items():
mydict_[k].append(v)
mydict = dict(mydict_)
print(mydict)
I am getting:-
mylist = [{'a': 'banana', 'banana'}, {'b': 'apple', 'apple'}, {'c': 'grapes', 'grapes'}]
Do this in your loop:
for x in mylist:
for k,v in x.items():
if(k in mydict):
mydict[k].append(v)
else:
mydict[k]=[v]
from collections import defaultdict
new_dict = defaultdict(list)
for key_value_pair in mylist:
key, value = list(key_value_pair.items())[0]
new_dict[key].append(value)
ans_dict = dict(new_dict)
I have the following for instance:
x = [{'A':1},{'A':1},{'A':2},{'B':1},{'B':1},{'B':2},{'B':3},{'C':1},{'D':1}]
and I would like to get a dictionary like this:
x = [{'A': [1,2], 'B': [1,2,3], 'C':[1], 'D': [1]}]
Do you have any idea how I could get this please?
You could use a collections.defaultdict of sets to collect unique values, then convert the final result to a dictionary with values as lists using a dict comprehension:
from collections import defaultdict
lst = [{'A':1},{'A':1},{'A':2},{'B':1},{'B':1},{'B':2},{'B':3},{'C':1},{'D':1}]
result = defaultdict(set)
for dic in lst:
for key, value in dic.items():
result[key].add(value)
print({key: list(value) for key, value in result.items()})
Output:
{'A': [1, 2], 'B': [1, 2, 3], 'C': [1], 'D': [1]}
Although its probably better to add your data directly to the defaultdict to begin with, instead of creating a list of singleton dictionaries(don't recommend this data structure) then converting the result.
Using dict.setdefault
Ex:
x = [{'A':1},{'A':1},{'A':2},{'B':1},{'B':1},{'B':2},{'B':3},{'C':1},{'D':1}]
res = {}
for i in x:
for k, v in i.items():
res.setdefault(k, set()).add(v)
#or res = [{k: list(v) for k, v in res.items()}]
print(res)
Output:
{'A': {1, 2}, 'B': {1, 2, 3}, 'C': {1}, 'D': {1}}
Probelm statement:
response= [{'HotelId': 8, 'IsFast': False, 'Payload': {'HotelInstaceId': 8, 'IsResetNeeded': False, 'HotelType': 'test', 'Product': {'Family': 'Times', 'Model': 'Roman', 'Type': 'Visible', 'Vendor': 'Royal'}, 'Hotel': {'DisplayBrightness': 80, 'LedColor': None, 'Location': '', 'Name': 'testing'}}}]
I want to verify the value of name "testing".
My code:
result = response["Data"][0]["Payload"]["Name"]
if result == "testing":
print("pass")
else:
print("fail")
New code:
tests = [{'a': 1},
{'b': {'a': 2}},
{'a': 3, 'b': {'a': 4}},
{'a': {'b': 5}},
{'a': {'a': 6}}]
def recursively_find_dict_values(self, d, tests, key="HotelType"):
output = []
for i, v in d.items():
if i == key:
output.append(v)
if isinstance(v, dict):
output.extend(self.recursively_find_dict_values(v, key, tests))
return output
for t in tests:
recursively_find_dict_values(t, key="HotelType")
i will get the response from another function and that response i will send to "recursively_find_dict_values" func as a argument..
Example inputs:
Input keys Output
"Name" "testing"
"DisplayBrightness" 80
"HotelType" "test"
but i want to do in generic way like if i pass "Name" or "DisplayBrightness" or any key to the function it should return the value and also if keys in nested dictionary then also it should return the value.
How can i achieve this?
I think this may be able to help you:
def recursively_find_dict_values(d, key):
output = []
for i,v in d.items():
if i == key:
output.append(v)
if isinstance(v, dict):
output.extend(recursively_find_dict_values(v, key))
return output
tests = [{'a': 1},
{'b': {'a': 2}},
{'a': 3, 'b': {'a': 4}},
{'a': {'b': 5}},
{'a': {'a': 6}}]
for t in tests:
print(recursively_find_dict_values(t, 'a'))
Try it online!
I would check all the examples to see if the functionality is to your liking. Note that if the value of 'a' is a dict, it will add a dict to the list, and if the dict value of 'a' also has a key 'a', both levels will be added to the dict (see the fifth example). Also, even if there is only one match, it will still return a list.
In this example, d is the name of your input dict:
# Getting all the values of key in d:
values = recursively_find_dict_values(d, key)
# Checking if key has value v in d:
if v in recursively_find_dict_values(d):
print('Success!')