Remove duplicate of a dictionary from list - python

How can i remove duplicate of the key "name"
[
{
'items':[
{
'$oid':'5a192d0590866ecc5c1f1683'
}
],
'image':'image12',
'_id':{
'$oid':'5a106f7490866e25ddf70cef'
},
'name':'Amala',
'store':{
'$oid':'5a0a10ad90866e5abae59470'
}
},
{
'items':[
{
'$oid':'5a192d2890866ecc5c1f1684'
}
],
'image':'fourth shit',
'_id':{
'$oid':'5a106fa190866e25ddf70cf0'
},
'name':'Amala',
'store':{
'$oid':'5a0a10ad90866e5abae59470'
}
}
]
I want to marge together dictionary with the same key "name"
Here is what i have tried
b = []
for q in data:
if len(data) == 0:
b.append(q)
else:
for y in b:
if q['name'] != y['name']:
b.append(q)
but after trying this the b list doesn't return unique dictionary that i wanted

You loop through the assembled list and if you find a dict with a different name, you add the current dict. The logic should be different: only add it if you don't find one with the same name!
That being said, you should maintain a set of seen names. That will make the check more performant:
b, seen = [], set()
for q in data:
if q['name'] not in seen:
b.append(q)
seen.add(q['name'])

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]

Dynamic length list of objects where each object's key-values are reassigned regardless of which list index is specified, but static list functions

First question here, so go easy on me.
I am attempting to assign a list of objects which represent an accumulator of 1s and 0s at each index location of a large input of binary strings ex: 011011101.
I wanted to read the first row of my input to get the length of the binary string, and then assign a variable that looks like -> "[ {0:0, 1:0} ] * len(n)" for the sake of brevity, I know that all rows will be a length of 12.
My objective: loop over each item in a row, and add 1 to either the 1 or 0 at that index location's object key. -> "arr[i][v] += 1"
i represents both the string index AND the object I want to access in the dynamically sized array
v represents the key(0 or 1) of the object at i location that i want to increment by 1
In this way I can figure out how many 1s or 0s are at each position of a given input.
simplified code:
`
input = ["010101101100", "110001101101"]
arr = [{ 0:0,1:0 }] * len(input[0])
for row in input:
for i, v in enumerate(row):
v = int(v)
arr[i][v] += 1
print(arr)
`
WRONG Result!
However, if I explicitly set the list as such:
input = ["010101101100", "110001101101"]
arr = [
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 },
{ 0:0,1:0 }
]
for i, v in enumerate(input):
v = int(v)
arr[i][v] += 1
print(arr)
The correct Answer!
What exactly is going on here? Why is the loop that accesses the dynamic list applying the addition to each object and corresponding key-value pair?
I'm sure it is some computer science thing that I'm just not getting.
The only reason this is sort of not making my head explode is that I could see the input, and I could just set the list explicitly, but if the length was unknown it would be an issue
When you use *, Python creates a list where each element references the same object. Thus, modifying one element ends up modifying all of them.
arr = [{0:0, 1:0}] * 12 # this creates a list where every element is the same dictionary
arr = [{0:0, 1:0} for _ in range(12)] # this creates a list containing 12 independent dictionaries

Python3 - loop through list with mulitple dictionaries

sorry I am rather a beginner when it comes to python.
I have a list like this:
"list": [
{
"id": 12345,
"name": "test"
},
{
"id": 12453,
"value": "value1",
"field": "test",
}
]
When looping through several of such lists I want it to print the "name" key from the upper dictionary but only if the condition is met that "value": "value1", is present but this is in a different dictionary.
I tried with stuff like: if 'value' in event.keys():
but I cant manage to only print this "name" key if the other condition is met. any suggestions?
Below one way of doing it, it is going through all key/value of all dictionnaries so it's probably not efficient but will adapt to several possibility.
I don't know if name can be in the list several times, the below code will keep the last occurrence if it happens.
I made it a function so that you can use it easily on several similar lists. It returns None if the criteria was not met, the value of name if it was.
def get_valid_name(dict_list, target_value):
keep_name = False
current_name = None
for d in dict_list:
for key, val in d.items():
if key == "name":
current_name = val
elif key == "value" and val == target_value:
keep_name = True
return current_name if keep_name else None
for l in [original_list]:
result = get_valid_name(l, "value1")
if result is not None:
print(result)

check if the value in a dict is not empty?

I have a dict theaterinfo like this :
"Showtimes":{
"New York": [
{
"Times": {},
"theaterid": 61,
}
]
"Ohio": [
{
"Times": {'2015-01-10',
'2015-01-11'},
"theaterid": 1,
}
]
}
How can I deal with that if Times in empty,don't print it out??
An empty dictionary evaluates to a boolean False while a non-empty dict evaluates to True, so you can write
if my_dict['Times']:
print(my_dict['Times'])
You need to iterate over the dict["Showtimes"] items then access the dict in the list using the Times key and check using an if which will return False for an empty dict.
d = {"Showtimes":{
"New York": [
{
"Times": {},
"theaterid": 61,
}
],
"Ohio": [
{
"Times": {'2015-01-10',
'2015-01-11'},
"theaterid": 1,
}
]
}}
for k,v in d["Showtimes"].iteritems():
if v[0]["Times"]:
print(k,v)
('Ohio', [{'theaterid': 1, 'Times': set(['2015-01-10', '2015-01-11'])}])
One thing to be careful of is if you have a value like 0, this will also return False so if you only want to check if the value is an empty dict use if v[0]["Times"] != {}
If you want to check all values of Times and only print the full dict if there are no empty Times values you can use all which will short circuit on the first occurrence of an empty value:
if all(v[0]["Times"] for v in d["Showtimes"].itervalues()):
print(d)
Or reverse the logic with any:
if not any(not v[0]["Times"] for v in d["Showtimes"].itervalues()):
print(d)
If there is a chance a dict won't have a Times key use v[0].get("Times",1)

List of values for a key in List of list of dictionaries?

Suppose I have a list of a list of dictionaries.
I'm pretty sure Python has a nice and short way (without writing 2 for loops) to retrieve the value associated with the key. (Every dictionary has a key).
How can I do this?
Edit : There is a sample (JSON representation) of the input
[
[
{
"lat": 45.1845931,
"lgt": 5.7316984,
"name": "Chavant",
"sens": "",
"line" : [],
"stationID" : ""
},
{
"lat": 45.1845898,
"lgt": 5.731746,
"name": "Chavant",
"sens": "",
"line" : [],
"stationID" : ""
}
],
[
{
"lat": 45.1868233,
"lgt": 5.7565727,
"name": "Neyrpic - Belledonne",
"sens": "",
"line" : [],
"stationID" : ""
},
{
"lat": 45.1867322,
"lgt": 5.7568569,
"name": "Neyrpic - Belledonne",
"sens": "",
"line" : [],
"stationID" : ""
}
]
]
As output I'd like to have a list of names.
PS: Data under ODBL.
If you need all names in flat list:
response = # your big list
[d.get('name') for lst in response for d in lst]
if you want to get result with inner list:
[[d.get('name') for d in lst] for lst in response]
Call your list of lists of dictionaries L. Then you can retrieve all names using a list comprehension by iterating through each sublist and then each dictionary.
Demo
>>> vals = [ d['name'] for sublist in L for d in sublist ]
>>> vals
[u'Chavant', u'Chavant', u'Neyrpic - Belledonne', u'Neyrpic - Belledonne']
Note that this returns a flattened list of all names (and that 'Chavant' appears twice, since it appears twice in your input).

Categories

Resources