1

I want to replace a number in this 2d array if the username already exists.

[["bob man", "0"], ["bill kill", "5"], ["nick", "5"]]

For example, when I receive the username "bob man", with the new number 44. I want to search my array and check if this username exists, and replace the number. If it doesn't exist, I want to append it to the array.

[["bob man", "44"], ["bill kill", "5"], ["nick", "5"]]

Is there a better way of storing this? I am new to python, and simple stuff like this seems much more complex than in js etc. Objects?

2
  • 1
    Instead of using list of lists(2d array) you can use dictionary to store data, because lookup's in dictionary are very fast compared to lists. Commented Apr 24, 2020 at 18:41
  • @ShubhamSharma Thanks! I knew there had to be much easier ways to do this! Commented Apr 24, 2020 at 18:43

1 Answer 1

1

You can use numpy structured array if you would like to keep the order:

a = np.array([("bob man", 0), ("bill kill", 5), ("nick", 5)], dtype=[('name', 'U10'), ('value', 'i4')])
new_entry = np.array([('bob man', 44)], dtype=[('name', 'U10'), ('value', 'i4')])

if new_entry['name'] in a['name']:
  a['value'][a['name']==new_entry['name']] = new_entry['value']
else:
  a = np.append(a, new_entry)

I expect it to be faster than dictionaries, specially if you want to add more than one entry, you can include them all in new_entry and change code a bit to check array-wise to be faster.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.