I have a Python list called "results" that has dictionaries as its values:
results = [
{
'postingStatus': 'Active',
'postEndDate': '1601683199000',
'boardId': '_internal',
'postStartDate': '1591084714000)'
},
{
'postingStatus': 'Expired',
'postEndDate': '1601683199000',
'boardId': '_external',
'postStartDate': '1591084719000)'
}
]
How would I create a list that gets all the values from the dictionary where the 'boardID' value is '_internal' (but ignores the dictionary where 'boardID' is '_external')? As an end result, I'm hoping for a list with the following contents:
['Active','1601683199000','_internal','1591084714000']
You can use list-comprehension:
out = [v for d in results for v in d.values() if d["boardId"] == "_internal"]
print(out)
Prints:
['Active', '1601683199000', '_internal', '1591084714000)']
without using List-comprehension
for items in results:
if items['boardId'] == '_internal':
lst1 = list(items.values())
print(lst1)
Related
I am not able to match the dict values with dict keys because for some dict contains two values.
my_dict = {
'Incident':'INC, Incident',
'Minor Enchancement':'Change',
'ServiceRequest':'SR, ServiceRequest'
}
input:
new_list= ['Incident','Inc','SR','Change']
output:
new_list = ['Incident','Incident','Minor Enchancement','Service Request']
i want read the list and match with dictionary . some key contains two values in the dictionary how can we match dict ?
Here is a better organization:
xlate = {
'INC': 'Incident',
'Inc': 'Incident',
'Change': 'Minor Enhancement',
'SR': 'ServiceRequest'
}
words = ['Incident','Inc','SR','Change']
new_list = []
for w in words:
new_list.append( xlate.get(w, w) )
print(new_list)
Output:
['Incident', 'Incident', 'ServiceRequest', 'Minor Enhancement']
Note that I use .get(w,w) which will pass "not found" entries through unchanged.
You want to invert the keys and values in the original dictionary, and split the values to produce multiple keys:
my_dict = {
'Incident':'INC, Incident, Inc', #note that I added another alias
'Minor Enchancement':'Change',
'ServiceRequest':'SR, ServiceRequest'
}
reversed_dict = {}
for key in my_dict:
items = [x.strip() for x in my_dict[key].split()]
for i in items:
reversed_dict[i] = key
assert reversed_dict['Incident'] == 'Incident'
assert reversed_dict['Inc'] == 'Incident'
Note that there is no 'magic' way to navigate between using Inc and INC, so if you want to be able to handle either case you need to include them as options.
i want loop like this but getting everything instead of only the 1st one.
from collections import OrderedDict
myList = OrderedDict(
{
'ID': ["1stID", "2ndID","3ndID"], 'ChannelID': ["1stChannel", "2ndChannel","3ndChannel"]
})
first_values = [v[0] for v in myList.values()]
print(first_values)
OUTPUT
['1stID', '1stChannel']
instead of
['1stID', '1stChannel']
DESIRED OUTPUT:
['1stID', '1stChannel']
['2stID', '2stChannel']
['3stID', '3stChannel']
You can use zip() to combine two list and get the combined pairs, as follows:
from collections import OrderedDict
myList = OrderedDict(
{
'ID': ["1stID", "2ndID", "3ndID"],
'ChannelID': ["1stChannel", "2ndChannel", "3ndChannel"]
})
pairs = zip(myList['ID'], myList['ChannelID'])
# list(pairs) -> [('1stID', '1stChannel'), ('2ndID', '2ndChannel'), ('3ndID', '3ndChannel')]
for pair in pairs:
print(list(pair))
Result:
['1stID', '1stChannel']
['2ndID', '2ndChannel']
['3ndID', '3ndChannel']
Other method (if you don't want to use key names):
from collections import OrderedDict
myList = OrderedDict(
{
"ID": ["1stID", "2ndID", "3ndID"],
"ChannelID": ["1stChannel", "2ndChannel", "3ndChannel"],
}
)
for a in zip(*myList.values()):
print(a) # or list(a) for lists instead of tuples
Prints:
('1stID', '1stChannel')
('2ndID', '2ndChannel')
('3ndID', '3ndChannel')
You misunderstood the structure you are building so you are not accessing it correctly.
mylist is a 2 element dictionary. each of the element are lists of length 3.
There is no connection between the positional elements of each other than the position.
See code below how I extracted and printed the data.
There may be an idiomatic way to do this in python more cleanly
but this served to show the structure clearly.
from collections import OrderedDict
myList = OrderedDict(
{
'ID': ["1stID", "2ndID", "3ndID"],
'ChannelID': ["1stChannel", "2ndChannel", "3ndChannel"]
})
first_values = [v[0] for v in myList.values()]
print(first_values)
#
# print out the values of the objects in the list
for v in myList.values():
print(v)
# extract the two lists
vid, vchan = myList.values()
# print out the whole list in one statement
print("all of vid ", vid)
print("all of vchan ", vchan)
# print out the element of the lists position by position
for i in range(len(vid)):
print(i, "th list item ", vid[i], vchan[i])
I have a list of dictionary something like this:
list = [
{
"ENT_AUT":[
"2018-11-27"
]
},
{
"ENT_NAT_REF_COD":"C87193"
},
{
"ENT_NAM":"MONEYBASE LIMITED"
},
{
"ENT_NAM_COM":"MONEYBASE LIMITED"
},
{
"ENT_ADD":"Ewropa Business Centre, Triq Dun Karm"
},
{
"ENT_TOW_CIT_RES":"Birkirkara"
},
{
"ENT_POS_COD":"BKR 9034"
},
{
"ENT_COU_RES":"MT"
}
]
Here every dictionary will always contain only one key value pair. Now I need to know the value of ENT_NAM, ENT_AUT and etc all fields.
I tried something like this:
ENT_NAM = (list[2].values())[0]
print('ENT_NAM = ', ENT_NAM)
It works perfectly for this list but my problem is that the 'ENT_NAM' containing dictionary will not always be on the 2nd index of the list. How can I generalize this solution so that even if the order of the dictionary under the list changes, I always find a perfect solution?
What you are describing is a search problem. Here the naive solution is probably fine:
def get_prop(dicts, k):
return next(x[k] for x in dicts if k in x)
get_prop(l, "ENT_NAM")
Incidentally, don't call your variable list: it shadows a builtin.
If you need to use this data more than about 3 times I would just reduce it to a dict:
def flatten(dicts):
iterdicts = iter(dicts)
start = next(iterdicts)
for d in iterdicts:
start.update(d)
return start
one_dict = flatten(list_of_dicts)
one_dict["ENT_NAM"]
(There are plenty of other ways to flatten a list of dicts, I just currently think the use of iter() to get a consumable list is neat.)
As jasonharper said in the comments, if it is possible, the data should be formulated as a single dictionary.
If this cannot happen, you can retrieve the value of ENT_NAM using:
print(list(filter(lambda elem: "ENT_NAM" in elem.keys(), my_list))[0]["ENT_NAM"])
Returns:
MONEYBASE LIMITED
Note: list has been renamed to my_list since list is a reserved Python keyword
If all of the keys are unique, you can flatten the list of dictionaries into a dictionary with a straightforward dictionary comprehension.
Note: you don't want to use list as a name for a variable, as it is an important built-in type. Use something like lst instead.
{ k: v for d in lst for k, v in d.items() }
Result:
{'ENT_AUT': ['2018-11-27'], 'ENT_NAT_REF_COD': 'C87193',
'ENT_NAM': 'MONEYBASE LIMITED', 'ENT_NAM_COM': 'MONEYBASE LIMITED',
'ENT_ADD': 'Ewropa Business Centre, Triq Dun Karm',
'ENT_TOW_CIT_RES': 'Birkirkara', 'ENT_POS_COD': 'BKR 9034',
'ENT_COU_RES': 'MT'}
Getting the value for key 'ENT_NAM' is now just:
{ k: v for d in lst for k, v in d.items() }['ENT_NAM']
I am trying to filter a JSON array based on a value contained in each of the arrays. Provided some user input, I only want to return relevant values based on the type.
Sample json:
{
"routes": [
{
"name": "Golden Shower",
"type": "Boulder",
"rating": "V5",
"stars": 5,
"starVotes": 131,
"pitches": ""
},
{
"name": "Girls Only",
"type": "Sport",
"rating": "5.10a",
"stars": 4.9,
"starVotes": 156,
"pitches": "1"
}
],
"success": 1
}
I have attempted to use a few variations of a code sample provided on a similar question, but am running in to issues due to slightly more complex data structure. See: how to filter json array in python
I have tried a few variations of code. All of the errors center around improper use of indices. Some things I've tried.
routeData = routesByGpsResp.json()
input_dict = routeData
output_dict = [x for x in input_dict if x['type'] == 'Sport']
error: sting indices must be integers
output_dict = [x for x in input_dict.items() if ['routes'][x]['type'] == 'Sport']
error: list indices must be integers or slices, not tuple
I was able to print a list of route names using for statement an index, but cannot seem to figure it out for list comprehension.
for key in range(len(routeData['routes'])):
print(routeData['routes'][key]['name'])
Is list comprehension the wrong way to go here? Should I be using a for statement instead?
Any help is appreciated!
Note: all your attempts are list comprehensions, while the variable name suggests a dict comprehension ([Python]: PEP 274 -- Dict Comprehensions).
Here's an example how you could get output_dict (and below, output_list) based on your input_dict, and the condition(s). As a note: the dict comprehension nests a list comprehension (which alone constitutes the 2nd example) for the "routes" key, while for all the other keys leaves the values unchanged:
>>> output_dict = {k: v if k != "routes" else [i for i in v if i["type"] == "Sport"] for k, v in input_dict.items()}
>>>
>>> from pprint import pprint
>>>
>>> pprint(output_dict)
{'routes': [{'name': 'Girls Only',
'pitches': '1',
'rating': '5.10a',
'starVotes': 156,
'stars': 4.9,
'type': 'Sport'}],
'success': 1}
>>>
>>> # Or if you only want the list
...
>>> output_list = [i for i in input_dict.get("routes", list()) if i["type"] == "Sport"]
>>>
>>> pprint(output_list)
[{'name': 'Girls Only',
'pitches': '1',
'rating': '5.10a',
'starVotes': 156,
'stars': 4.9,
'type': 'Sport'}]
In your first attempt:
output_dict = [x for x in input_dict if x['type'] == 'Sport']
x in input_dict iterates over the keys, so you are doing "routes"['type'], but strings are indexes by integers, and not by a string,
hence the error string indices must be integers
In your second attempt:
output_dict = [x for x in input_dict.items() if ['routes'][x]['type'] == 'Sport']
['routes'] is a list, and x is a tuple of (key,value) obtained by iterating over the dictionary input_dict, so ['routes'][x] raises a error: list indices must be integers or slices, not tuple
The right way for a list-comprehension, as already pointed out by #cs95, is to iterate over the list of routes by for x in input_dict.get('routes'), get the dictionary for the value of key type that matches Sport
print([x for x in input_dict.get('routes') if x.get('type') == 'Sport'])
The output is
[{'name': 'Girls Only', 'type': 'Sport', 'rating': '5.10a', 'stars': 4.9, 'starVotes': 156, 'pitches': '1'}]
I have a list of dictionaries. e.g:
list = [ {list1}, {list2}, .... ]
One of the key-value pair in each dictionary is another dictionary.
Ex
list1 = { "key1":"val11", "key2":"val12", "key3":{"inkey11":"inval11","inkey12":"inval12"} }
list2 = { "key1":"val21", "key2":"val22", "key3":{"inkey21":"inval21","inkey22":"inval22"} }
I was thinking of getting all values of key3 in the all the dictionaries into a list.
Is it possible to access them directly (something like list[]["key3"] ) or do we need to iterate through all elements to form the list?
I have tried
requiredlist = list [ ] ["key3"].
But it doesn't work.
The final outcome I wanted is
requiredlist = [ {"inkey11":"inval11","inkey12":"inval12"}, {"inkey21":"inval21","inkey22":"inval22"} ]
I think a list comprehension would work well here:
[innerdict["key3"] for innerdict in list]
Try this:
list1["key3"]
Notice that list1 and list2 as you defined them are dictionaries, not lists - and the value of "key3" is a set, not a list. You're confounding {} with [], they have different meanings.
To access an element is a dictionary you must do the following:
dict_name[key_name] #in this case: list1[key3]
Try this:
newlist = []
list = [{ "key1":"val11", "key2":"val12", "key3":{dict1} },{ "key1":"val21", "key2":"val22", "key3":{dict1} }]
for innerdict in list:
newlist += list(innerdict["key3"])
print newlist #This will give all the values of key3 in all the dictionaries
if dict1 in the lists is a set then the above example will work good, but if it is a dictionary then it will give a list but ONLY the keys will be included so if it is a dictionary try this:
newlist = []
list = [{ "key1":"val11", "key2":"val12", "key3":{dict1} },{ "key1":"val21", "key2":"val22", "key3":{dict1} }]
for innerdict in list:
newlist.append(innerdict["key3"])
print newlist #This will give all the values of key3 in all the dictionaries