0

I cannot figure out how to search in the follow list/array (stored in self._map_commodities) and the data is obtained from JSON.

The problem: I want to locate "wood" in the array and return the "size" value related to it

I have tried to use index(), but I cannot get it to work. T

class MyClass1(object):

    def __init__(self):
        self._data = ''
        self.list_commodities = []
        self._map_commodities = []

    def create_commodity_market(self):
        for commodity in self._data['commodities']:
            self.list_commodities.append(commodity['id'])
            self._map_commodities.append(commodity)

    def from_json(self):
        import json
        self._data = json.loads('{"commodities":[{"id":"food","size":"1.0"},{"id":"wood","size":"1.0"},{"id":"ore","size":"1.0"},{"id":"metal","size":"1.0"},{"id":"tools","size":"1.0"}]}')


x = MyClass1()
x.from_json()
x.create_commodity_market()
print(x.list_commodities)
print(x._map_commodities)
####print(x._map_commodities.index("wood")) # I want it to print the size-value of the wood object

Thank you in advance.

3
  • What output does this script return? Commented Mar 11, 2015 at 20:36
  • You need to provide us with _map_commodities method Commented Mar 11, 2015 at 20:43
  • ['food', 'wood', 'ore', 'metal', 'tools'] [{'id': 'food', 'size': '1.0'}, {'id': 'wood', 'size': '1.0'}, {'id': 'ore', 'size': '1.0'}, {'id': 'metal', 'size': '1.0'}, {'id': 'tools', 'size': '1.0'}] I need a way to search/match id's (food, wood, ore, metal, tools) and return the "size" related to them. I know everyone has size: 1.0 but they could be different. Commented Mar 11, 2015 at 20:44

4 Answers 4

1

Basically what you want is:

print next(y['size'] for y in x._map_commodities if y['id'] == 'wood')

Which will throw an StopIteration exception if none of your items have the id 'wood'.

More generally, add a method like this to MyClass1:

def size_from_id(self, id_name):
    try:
        return next(y['size'] for y in self._map_commodities if y['id'] == id_name)
    except StopIteration:
        return None

Then you can call x.size_from_id('wood').

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

Comments

0

A dictionary is more suitable for what you're trying to do:

class MyClass1(object):

def __init__(self):
    self._data = ''
    self._map_commodities = {}

def create_commodity_market(self):
    for commodity in self._data['commodities']:
        self._map_commodities[commodity['id']] = commodity['size']

def from_json(self):
    import json
    self._data = json.loads('{"commodities":[{"id":"food","size":"1.0"},{"id":"wood","size":"1.0"},{"id":"ore","size":"1.0"},{"id":"metal","size":"1.0"},{"id":"tools","size":"1.0"}]}')


x = MyClass1()
x.from_json()
x.create_commodity_market()
print(x._map_commodities["wood"])

Comments

0

You could use pandas to handle the data

import json
import pandas as pd

data = json.loads('{"commodities":[{"id":"food","size":"1.0"},{"id":"wood","size":"1.0"},{"id":"ore","size":"1.0"},{"id":"metal","size":"1.0"},{"id":"tools","size":"1.0"}]}')
df = pd.DataFrame.from_dict(data['commodities'])

# get the size of the row with id = 'wood'
size = df[df['id'] == 'wood']['size']
print size

# you can get the value alone, too
print size.values[0]

Comments

0

First of all you need to return the specific value on your function :

def from_json(self):
        import json
        self._data = json.loads('{"commodities":[{"id":"food","size":"1.0"},{"id":"wood","size":"1.0"},{"id":"ore","size":"1.0"},{"id":"metal","size":"1.0"},{"id":"tools","size":"1.0"}]}')
        return self._data

Then use indexing to get the related size of a word.for example :

x = MyClass1()
d=x.from_json()
print d['commodities'][1]['size']
u'1.0'

1 Comment

"return elf._data" should be "return self._data"

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.