Deleting a value in an array in Python [duplicate] - python

This question already has answers here:
Deleting list elements based on condition
(2 answers)
Closed 6 years ago.
I've created an array for my output by doing this:
for i in nameList
test_array.append({'Name': i, 'Email': memberMail, 'Department': memberDepartment})
However, later in the code, I must remove designated values in my test_array depending on their email. After that, I can easily print out what I need to my csv file.
How do I delete a specific entry from this sort of dictionary list?
For those curious, when I print the array currently it looks like this:
[{'Department': 'Public Works', 'Email': 'joe#xyz.gov', 'Name': 'Joe'}, {'Department': 'Infrastructure', 'Email': 'bob#xyz.gov', 'Name': 'Bob'}, {'Department': 'IT', 'Email': 'suzanne#xyz.gov', 'Name': 'Suzanne'}]

For when you not want to modify test_array
filtered_test_array = filter(lambda entry: entry['Email'] != 'email#example.com', test_array)

Try this:
for i in range(0,len(nameList)):
if nameList[i]['Email'] == 'abc#pqr.com" :
index = i;
del nameList[index];

Try like this.
list_ = [{'Department': 'Public Works', 'Email': 'joe#xyz.gov', 'Name': 'Joe'}, {'Department': 'Infrastructure', 'Email': 'bob#xyz.gov', 'Name': 'Bob'}, {'Department': 'IT', 'Email': 'suzanne#xyz.gov', 'Name': 'Suzanne'}]
for val in list_:
if val['Email'] == 'joe#xyz.gov':
list_.remove(val)
Result
[{'Department': 'Infrastructure', 'Email': 'bob#xyz.gov', 'Name': 'Bob'},
{'Department': 'IT', 'Email': 'suzanne#xyz.gov', 'Name': 'Suzanne'}]

You can iterate over the list and delete with respect to a unique value or a key. Something like this:
for entry in test_array:
if entry['Email'] == 'suzanne#xyz.gov':
test_array.remove(entry)

Related

How can I print a list without the first square brackets?

How can I print a list without the first square brackets?
[[{'id': '5b0cecebc15ae360393438c2', 'owner': {'id': '58ebd0b12c593e5253505ad4'}, 'linked_id': None, 'type': 'product', 'name': 'Трансформаторное масло Т-1500у'}]]
At the same time, it is necessary to preserve its essence of the list.
So that the parser can read the id.
items = response['data']
usr_ids = items[i]["owner"]["id"]
Simply print the first item of the list
lst = [[{'id': '5b0cecebc15ae360393438c2', 'owner': {'id': '58ebd0b12c593e5253505ad4'}, 'linked_id': None, 'type': 'product', 'name': 'Трансформаторное масло Т-1500у'}]]
print(lst[0])

Make a list of first item in every element of a dictionary

I am working with a dictionary from a file with an import. This is the dictionary:
[{'id': 76001,
'full_name': 'Alaa Abdelnaby',
'first_name': 'Alaa',
'last_name': 'Abdelnaby',
'is_active': False},
{'id': 76002,
'full_name': 'Zaid Abdul-Aziz',
'first_name': 'Zaid',
'last_name': 'Abdul-Aziz',
'is_active': False},
{'id': 76003,
'full_name': 'Kareem Abdul-Jabbar',
'first_name': 'Kareem',
'last_name': 'Abdul-Jabbar',
'is_active': False}]
What I want to do is get a list out of all the IDs:
player_ids = [76001,76002, 76003]
I have tried:
player_ids = []
for i in player_dict:
player_ids.append(player_dict[i]['id'])
but I get the error
TypeError: list indices must be integers or slices, not dict
So I get that 'i' is not the place but the actual item I am calling in the dictionary? But I'm not able to make much sense of this based on what I have read.
The pythonic way to do this is with a list comprehension. For example:
player_ids = [dict['id'] for dict in player_dict]
This basically loops over all dictionaries in the player_dict, which is actually a list in your case, and for every dictionary gets the item with key 'id'.
You can try list comprehension:
>>> [d['id'] for d in my_list]
[76001, 76002, 76003]
Here is how you can use a list comprehension:
player_dict = [{'id': 76001,
'full_name': 'Alaa Abdelnaby',
'first_name': 'Alaa',
'last_name': 'Abdelnaby',
'is_active': False},
{'id': 76002,
'full_name': 'Zaid Abdul-Aziz',
'first_name': 'Zaid',
'last_name': 'Abdul-Aziz',
'is_active': False},
{'id': 76003,
'full_name': 'Kareem Abdul-Jabbar',
'first_name': 'Kareem',
'last_name': 'Abdul-Jabbar',
'is_active': False}]
player_ids = [d['id'] for d in player_dict]
print(player_ids)
Output:
[76001, 76002, 76003]
Just append
player_ids.append(i['id'])

Extracting value for one dictionary key in Pandas based on another in the same dictionary

This is from an R guy.
I have this mess in a Pandas column: data['crew'].
array(["[{'credit_id': '54d5356ec3a3683ba0000039', 'department': 'Production', 'gender': 1, 'id': 494, 'job': 'Casting', 'name': 'Terri Taylor', 'profile_path': None}, {'credit_id': '56407fa89251417055000b58', 'department': 'Sound', 'gender': 0, 'id': 6745, 'job': 'Music Editor', 'name': 'Richard Henderson', 'profile_path': None}, {'credit_id': '5789212392514135d60025fd', 'department': 'Production', 'gender': 2, 'id': 9250, 'job': 'Executive In Charge Of Production', 'name': 'Jeffrey Stott', 'profile_path': None}, {'credit_id': '57892074c3a36835fa002886', 'department': 'Costume & Make-Up', 'gender': 0, 'id': 23783, 'job': 'Makeup Artist', 'name': 'Heather Plott', 'profile_path': None}
It goes on for quite some time. Each new dict starts with a credit_id field. One sell can hold several dicts in an array.
Assume I want the names of all Casting directors, as shown in the first entry. I need to check check the job entry in every dict and, if it's Casting, grab what's in the name field and store it in my data frame in data['crew'].
I tried several strategies, then backed off and went for something simple.
Running the following shut me down, so I can't even access a simple field. How can I get this done in Pandas.
for row in data.head().iterrows():
if row['crew'].job == 'Casting':
print(row['crew'])
EDIT: Error Message
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-138-aa6183fdf7ac> in <module>()
1 for row in data.head().iterrows():
----> 2 if row['crew'].job == 'Casting':
3 print(row['crew'])
TypeError: tuple indices must be integers or slices, not str
EDIT: Code used to get the array of dict (strings?) in the first place.
def convert_JSON(data_as_string):
try:
dict_representation = ast.literal_eval(data_as_string)
return dict_representation
except ValueError:
return []
data["crew"] = data["crew"].map(lambda x: sorted([d['name'] if d['job'] == 'Casting' else '' for d in convert_JSON(x)])).map(lambda x: ','.join(map(str, x))
To create a DataFrame from your sample data, write:
df = pd.DataFrame(data=[
{ 'credit_id': '54d5356ec3a3683ba0000039', 'department': 'Production',
'gender': 1, 'id': 494, 'job': 'Casting', 'name': 'Terri Taylor',
'profile_path': None},
{ 'credit_id': '56407fa89251417055000b58', 'department': 'Sound',
'gender': 0, 'id': 6745, 'job': 'Music Editor',
'name': 'Richard Henderson', 'profile_path': None},
{ 'credit_id': '5789212392514135d60025fd', 'department': 'Production',
'gender': 2, 'id': 9250, 'job': 'Executive In Charge Of Production',
'name': 'Jeffrey Stott', 'profile_path': None},
{ 'credit_id': '57892074c3a36835fa002886', 'department': 'Costume & Make-Up',
'gender': 0, 'id': 23783, 'job': 'Makeup Artist',
'name': 'Heather Plott', 'profile_path': None}])
Then you can get your data with a single instruction:
df[df.job == 'Casting'].name
The result is:
0 Terri Taylor
Name: name, dtype: object
The above result is Pandas Series object with names found.
In this case, 0 is the index value for the record found and
Terri Taylor is the name of (the only in your data) Casting Director.
Edit
If you want just a list (not Series), write:
df[df.job == 'Casting'].name.tolist()
The result is ['Terri Taylor'] - just a list.
I think, both my solutions should be quicker than "ordinary" loop
based on iterrows().
Checking the execution time, you may try also yet another solution:
df.query("job == 'Casting'").name.tolist()
==========
And as far as your code is concerned:
iterrows() returns each time a pair containing:
the key of the current row,
a named tuple - the content of this row.
So your loop should look something like:
for row in df.iterrows():
if row[1].job == 'Casting':
print(row[1]['name'])
You can not write row[1].name because it refers to the index value
(here we have a collision with default attributes of the named tuple).

Python get only values in each dictionary

I intend to get the values for each dictionary in array list and put the values in new dictionary.
There are two key,two values in each dictionary.
This is my array_list.
[{'Name': 'email',
'Value': 'mail#outlook.com'},
{'Name': 'name',
'Value': 'tester'},
{'Name': 'address',
'Value': 'abc'}]
My expected outcome (to get the both values in each dictionary):
{'email': 'mail#outlook.com',
'name': 'tester',
'address': 'abc'}
My current code:
outcome = {}
x = ""
for i in range(len(array_list)):
for key,value in array_list[i].items():
if key == 'Value':
x = value
elif key == 'Name':
outcome[value] = x
I still not able to get the expected outcome. Any helps?
l = [{'Name': 'email',
'Value': 'mail#outlook.com'},
{'Name': 'name',
'Value': 'tester'},
{'Name': 'address',
'Value': 'abc'}]
{k['Name'] : k['Value'] for k in l}
the result is
{'address': 'abc', 'email': 'mail#outlook.com', 'name': 'tester'}
You are almost correct. Just have some problems in if else.
After writing a code you should try to simulate your code by yourself. Please look carefully in you inner for loop. For each iteration either Name or Value will be set as if and elif is mutually exclusive. But the requirement is to create key-value in each iteration.
outcome = {}
array_list = [{'Name': 'email',
'Value': 'mail#outlook.com'},
{'Name': 'name',
'Value': 'tester'},
{'Name': 'address',
'Value': 'abc'}]
for i in range(len(array_list)):
keys = array_list[i].keys()
if 'Name' in keys and 'Value' in keys:
outcome[array_list[i]['Name']] = array_list[i]['Value']
It is almost same as your code but my thinking is different.

Getting a python dict.keys trail for each item

I have a python dict that looks like this
{'data': [{'data': [{'data': 'gen1', 'name': 'objectID'},
{'data': 'familyX', 'name': 'family'}],
'name': 'An-instance-of-A'},
{'data': [{'data': 'gen2', 'name': 'objectID'},
{'data': 'familyY', 'name': 'family'},
{'data': [{'data': [{'data': '21',
'name': 'objectID'},
{'data': 'name-for-21',
'name': 'name'},
{'data': 'no-name', 'name': None}],
'name': 'An-instance-of-X:'},
{'data': [{'data': '22',
'name': 'objectID'}],
'name': 'An-instance-of-X:'}],
'name': 'List-of-2-X-elements:'}],
'name': 'An-instance-of-A'}],
'name': 'main'}
The structure is repeating and its rule is like:
A dict contains 'name' and 'data'
'data' can contain a list of dicts
If 'data' is not a list, it is a value I need.
'name' is a just a name
The problem is that for each value, I need to know every info for each parent.
So at the end, I need to print a list with items that looks something like:
objectID=gen2 family=familyY An-instance-of-X_objectID=21 An-instance-of-X_name=name-for-21
Edit: This is only one of several lines I want as the output. I need one line like this for each item that doesn’t have a dict as 'data'.
So, for each data that is not a dict, traverse up, find info and print it..
I don't know every function in modules like itertools and collections. But is there something in there I can use? What is this called (when I am trying to do research on my own)?
I can find many "flatten dict" methods, but not like this, not when I have 'data', 'name' like this..
This is a wonderful example what recursion is good for:
input_ = {'data': [{'data': [{'data': 'gen1', 'name': 'objectID'},
{'data': 'familyX', 'name': 'family'}],
'name': 'An-instance-of-A'},
{'data': [{'data': 'gen2', 'name': 'objectID'},
{'data': 'familyY', 'name': 'family'},
{'data': [{'data': [{'data': '21',
'name': 'objectID'},
{'data': 'name-for-21',
'name': 'name'},
{'data': 'no-name', 'name': None}],
'name': 'An-instance-of-X:'},
{'data': [{'data': '22',
'name': 'objectID'}],
'name': 'An-instance-of-X:'}],
'name': 'List-of-2-X-elements:'}],
'name': 'An-instance-of-A'}],
'name': 'main'}
def parse_dict(d, predecessors, output):
"""Recurse into dict and fill list of path-value-pairs"""
data = d["data"]
name = d["name"]
name = name.strip(":") if type(name) is str else name
if type(data) is list:
for d_ in data:
parse_dict(d_, predecessors + [name], output)
else:
output.append(("_".join(map(str,predecessors+[name])), data))
result = []
parse_dict(input_, [], result)
print "\n".join(map(lambda x: "%s=%s"%(x[0],x[1]),result))
Output:
main_An-instance-of-A_objectID=gen1
main_An-instance-of-A_family=familyX
main_An-instance-of-A_objectID=gen2
main_An-instance-of-A_family=familyY
main_An-instance-of-A_List-of-2-X-elements_An-instance-of-X_objectID=21
main_An-instance-of-A_List-of-2-X-elements_An-instance-of-X_name=name-for-21
main_An-instance-of-A_List-of-2-X-elements_An-instance-of-X_None=no-name
main_An-instance-of-A_List-of-2-X-elements_An-instance-of-X_objectID=22
I hope I understood your requirements correctly. If you don't want to join the paths into strings, you can keep the list of predecessors instead.
Greetings,
Thorsten

Categories

Resources