iterate list and compare it's values with dict - python

I am dealing with 1. list of dictionaries and 2. list. I am trying to:
1. iterate through list (list1),
2. Match the list1's value with the ID of API response, if found- put entire dict in a new_dict
3. else skip
API response in Json format:
list_of_dict=[{"id":1500,
"f_name": "alex",
"age": 25
},
{"id" :1501,
"f_name":"Bob",
"age": 30
},
{"id" :1600,
"f_name":"Charlie",
"age": 35
}
...
]
And a list1:
list1=[1500,1501,1211.....]
According to this, 1500 & 1501 is present in list_of_dict so that entire dict will be added in new_dict.
My attempt:
new_dict=dict()
for i,val in enumerate(list1):
#assuming val found in dict
#so put it in new dict
print i ,"=",val
new_dict.update({"id": val,"name":name, "age":age})
What i see is this code taking only last item of the list and updates the dict.. but in my case, new_dict will contains two dictionaries with id 1500 and 1501. What i am missing?

list_of_dict = [{"id":1500,
"f_name": "alex",
"age": 25
},
{"id" :1501,
"f_name":"Bob",
"age": 30
},
{"id" :1600,
"f_name":"Charlie",
"age": 35
}
]
list1=[1500,1501,1211]
ret = filter(lambda x: x['id'] in list1, list_of_dict)
print ret
Check out the useful and simple filter function built-in to python. It iterates through an iterable (list) and returns only the items that return true for the provided function
In this case, our filtering function is:
lambda x: x['id'] in list1

list_of_dict = [{"id":1500,
"f_name": "alex",
"age": 25
},
{"id" :1501,
"f_name":"Bob",
"age" 30
},
{"id" :1600,
"f_name":"Charlie",
"age" 35
}
...
]
dicts = {d['id']:d for d in list_of_dict}
list1=[1500,1501,1211.....]
answer = [dicts[k] for k in list1 if k in dicts]

You can do this with a simple list comprehension, filtering the dicts by whether their id is in the list:
result = [d for d in list_of_dict if d["id"] in list1]
If your list1 is larger, you might want to turn it into a set first, so the lookup is faster:
list1_as_set = set(list1)
result = [d for d in list_of_dict if d["id"] in list1_as_set]

Related

python replace json list values without knowing the keys

I have this code snippet:
data = {
"links": [
{"key_name_not_known": "replace_by_first_value_in_list"},
{"key_name_not_known": "replace_by_second_value_in_list"},
]
}
list = ["hello1", "hello2"]
Here I want to replace both values "hello" in data["links"] ["keys"]? without knowing the key value by the two values in the list, in the right order.
A goal output would be:
data = {
"links": [
{"key_name_not_known": "hello1"},
{"key_name_not_known": "hello2"},
]
}
How can I do that ?
for index, obj in enumerate(data['links']):
for key,val in obj.items():
if len(list) > index:
data['links'][index][key] = list[index]

Python - Pull Out Values from Only Dictionaries that Meet a Certain Criteria

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)

create new dictionary from mapping list into dictionary

I want to create new dictionary by mapping list into dictionary, so the list item will be the key and the dictionary will be the value.
Students List :
[Student1,Student2,Student3]
dictionary:
{Math:90, CS:94, Since:89}
the expected result is one dictionary:
{
"Student1":{
Math:90
},
"Student2":{
CS:94
},
"Student3":{
Since:89
}
}
I tray this:
new_dic=dic()
new_dic = dic(zip(students,dic1)
output:
{
Student1:Math,
Student2:CS,
Student3:Since
}
but it give me unexpected result. also I try the solution here and it didn't works for me.
Use zip along with some modification to reproduce the inner dict structure
names = ["Student1", "Student2", "Student3"]
values = {"Math": 90, "CS": 94, "Since": 89}
result = {name: {course: val} for name, (course, val) in zip(names, values.items())}
Alternatively, you could use:
a = ['student1','student2','student3']
b = { "Math":90 , "CS":94, "Since":89 }
c = {k1: {k2: v} for (k1,k2,v) in zip(a, b.keys(), b.values())}

Flattening a dictionary <str, list> into a comprehensive list

So I've got the following dictionary from a server request:
dict = {"first": "Mark", "last": "Zuckerberg", "alternative": ["Zuck", "Facebook guy"]}
Which I'm looking to convert into a list like this:
result = ["Mark", "Zuckerberg", "Zuck", "Facebook guy"]
I'm really trying to keep it pythonic for personal satisfaction I guess. The closest I've been to is this, which you can tell it only gives me the nested list instead of what I'm actually looking for.
values = list(dict.values())
result = [item for sublist in values for item in sublist if isinstance(sublist, list)]
Thanks for any input.
You could do:
def flatten(s):
for e in s:
if isinstance(e, (tuple, list)):
yield from flatten(e)
else:
yield e
d = {"first": "Mark", "last": "Zuckerberg", "alternative": ["Zuck", "Facebook guy"]}
result = list(flatten(d.values()))
print(result)
Output
['Mark', 'Zuckerberg', 'Zuck', 'Facebook guy']
The flatten function will deal with arbitrary nested lists.

Get a list from the dictionary key in a list of dictionaries

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

Categories

Resources