Hello,
I do a new project with a Discord bot for a game (iRacing) to keep information during a race. I use pyirsdk and i look all source code to try to understand how it works.
However, I have a dict in a list and i'm blocked.
DriverInfo:
{
'DriverHeadPosX': -0.579,
'DriverHeadPosY': 0.398,
'DriverHeadPosZ': 0.571,
'Drivers':
[
{'CarIdx': 0, 'UserName': 'Enzo Foucaud', 'AbbrevName': '', 'Initials': '', 'UserID': 409133, 'TeamID': 0, 'TeamName': 'Enzo Foucaud', 'CarNumber': '64', 'CarNumberRaw': 64, 'CarPath': 'mercedesamggt3', 'CarClassID': 0, 'CarID': 72, 'CarIsPaceCar': 0, 'CarIsAI': 0, 'CarScreenName': 'Mercedes AMG GT3', 'CarScreenNameShort': 'Mercedes AMG GT3', 'CarClassShortName': None, 'CarClassRelSpeed': 0, 'CarClassLicenseLevel': 0, 'CarClassMaxFuelPct': '1.000 %', 'CarClassWeightPenalty': '0.000 kg', 'CarClassPowerAdjust': '0.000 %', 'CarClassColor': 16777215, 'IRating': 1, 'LicLevel': 1, 'LicSubLevel': 1, 'LicString': 'R 0.01', 'LicColor': '0xundefined', 'IsSpectator': 0, 'CarDesignStr': '1,dff000,1a4b9b,ffffff', 'HelmetDesignStr': '1,dff000,1a4b9b,ffffff', 'SuitDesignStr': '1,dff000,1a4b9b,ffffff', 'CarNumberDesignStr': '0,0,FFFFFF,777777,000000', 'CarSponsor_1': 0, 'CarSponsor_2': 0, 'CurDriverIncidentCount': 0, 'TeamIncidentCount': 0}
]
}
I do this to know if 'UserName' exist or not
DriversInfo_list = ir['DriverInfo']
print('DriverInfo:', DriversInfo_list)
for i in DriversInfo_list:
if i == 'Drivers':
print("Drivers Exists")
SoloDriver = DriversInfo_list['Drivers']
print(SoloDriver)
if [d['UserName'] for d in SoloDriver if 'UserName' in d]:
print('Username Exists')
Console :
DriverInfo: {...}
Drivers Exists
[{'CarIdx': 0, ...}]
Username Exists
Now, i want to extract many info of 'Drivers' (dict) in DriverInfo who is a list.
For example i want the value of UserName but i don't know how i can do this. I search during all the day .. ^^ i do many lesson to try this ^^
Thank's for your answer
Assume each driver dict in the Drivers list has exactly the same keys. Otherwise will throw KeyError. To avoid this error check if the key exists in lambda.
drivers = ir['DriverInfo']['Drivers']
result = list(map((lambda x: x['UserName']), drivers))
It depends if all DriversInfo items contain only a list of one dictionary in the driver key. But you can do like:
DriversInfo_list = ir['DriverInfo']
for soloDriverInfo in DriversInfo_list['Drivers']:
#Iterate in list of driver key
print(f"username: {soloDriverInfo['UserName']}, car: {soloDriverInfo['CarScreenName']}")
Related
I have created a custom module, in this module, I have a button. The button should create a delivery order in the inventory module ( just like the confirm button in the Sales module). But when I click it, It gives me the error in the pic, and this is my code.
def delivery_order(self):
delivery = self.env['stock.picking'].create({
# 'type': 'out_invoice',
'state': 'assigned',
'picking_type_id': 1,
'partner_id': self.partner_id.id,
'location_id': 1,
'location_dest_id': 1,
'origin': self.name,
'move_ids_without_package': [(0, 0, {
'product_id': self.product_id.id,
'product_uom_qty': self.selected_weight,
'picking_type_id': 1,
})]})
return delivery
You should add name field in the create method because it is a mandatory field, which causes the error.
I am calling an API provided by Steam to get user details. I am using Python's requests and JSON library to call this. My code:
import requests
import json
response = requests.get("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=76561198330357188")
data = response.json()
print(data['response'])
The output comes:
{'players': [{'steamid': '76561198330357188', 'communityvisibilitystate': 3, 'profilestate': 1, 'personaname': 'saditstar', 'profileurl': 'https://steamcommunity.com/id/saditrahman/', 'avatar': 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f8/f8d41f4064e1df34b1b5c439e775e222fb171ed3.jpg', 'avatarmedium': 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f8/f8d41f4064e1df34b1b5c439e775e222fb171ed3_medium.jpg', 'avatarfull': 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f8/f8d41f4064e1df34b1b5c439e775e222fb171ed3_full.jpg', 'avatarhash': 'f8d41f4064e1df34b1b5c439e775e222fb171ed3', 'lastlogoff': 1628598684, 'personastate': 1, 'realname': 'Kowsar Rahman Sadit', 'primaryclanid': '103582791429521408', 'timecreated': 1473564722, 'personastateflags': 0, 'loccountrycode': 'BD'}]}
My simple question is how can I access elements such as profilestate or like personaname?
You can access these values like the following sample.
>>> vals = {'players': [{'steamid': '76561198330357188', 'communityvisibilitystate': 3, 'profilestate': 1, 'personaname': 'saditstar', 'profileurl': 'https://steamcommunity.com/id/saditrahman/', 'avatar': 'http 8d41f4064e1df34b1b5c439e775e222fb171ed3_medium.jpg', 'avatarfull': 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f8/f8d41f4064e1df34b1b5c439e775e222fb171ed3_full.jpg', 'avatarhash': 'f8d41f4064e1df34b1b5c439e775e222fb171ed3', 'lastlogoff': 1628598684, 'personastate': 1, 'realname': 'Kowsar Rahman Sadit', 'primaryclanid': '103582791429521408', 'timecreated': 1473564722, 'personastateflags': 0, 'loccountrycode': 'BD'}]}
>>> [item.get('profilestate') for item in vals['players'] ]
[1]
I am trying to return just two fields from my MongoDB database and this query correct sends back my username and posts from the client:
db.users.find({'email_address': /^johnny/}, {'username': 1, 'user_posts': 1, '_id': 0});
I'm trying to switch this to PyMongo so I can query in Python and my query looks like this:
regx = Regex('^{0}'.format('johnny'))
query = {'postcode': regx}, {'username': 1, 'user_posts': 1, '_id': 0}
user_list = mycol.find(query).limit(5)
The bit where it's failing is here:
{'username': 1, 'user_posts': 1, '_id': 0}
As without this filter the documents are sent in full fine. With that I get this error message from PyMongo:
TypeError: filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping
I assume that my filter is malformed and it's no longer a dictionary so have tried various alternatives of wrapping in quotes and then .format() etc but cannot seem to hit the magical combination.
The problem is that the following is not a dictionary but a tuple of two dictionaries:
query = {'postcode': regx}, {'username': 1, 'user_posts': 1, '_id': 0}
if you wanted to use it directly you could do it with
user_list = mycol.find(query[0], query[1]).limit(5)
but probably best to actually assign it to two separate variables like so
query, filter = {'postcode': regx}, {'username': 1, 'user_posts': 1, '_id': 0}
and then
user_list = mycol.find(query, filter).limit(5)
Turned out it was quite easy.. I just needed to have two dictionaries. 1 for the query and the other for the filter.
regx = Regex('^{0}'.format('johnny'))
filter_stuff = {'username': 1, 'user_posts': 1, '_id': 0}
Then just build the full query as follows:
user_list = mycol.find(query, filter_stuff).limit(5)
This question already has answers here:
List on python appending always the same value [duplicate]
(5 answers)
Creating a list of dictionaries results in a list of copies of the same dictionary
(4 answers)
Closed 4 years ago.
I am trying to append dictionaries to a list here, problem is after appending both "Chrome" and "Firefox" values to the "list" i see only firefox.exe in list for both entries ..
any help is really appreciated.
See the print statement of dictionary where both values are different.
MyItems = ["ChromeSetup.exe","firefox.exe"]
listofitems = [{"appId": "ChromeID", 'id': "0","name": 'ChromeSetup.exe','_id': 'ChromeUnique'},{"appId": "FireFoxID", 'id': "0","name": 'firefox.exe','_id': 'FireFoxUnique'} ]
__id = ""
appId = ""
result = []
Dict = {"installerParameters":"","managedApp":{"_id":__id, "appId":appId},"postInstallAction":0,"postInstallScript":{"_id":"0"},"preInstallScript":{"_id":"0"}}
for app in MyItems:
for items in listofitems:
if items['name'] == app:
Dict["managedApp"]["_id"] = items['_id']
Dict["managedApp"]["appId"] = items['appId']
print("Dictionery",Dict)
result.append(Dict)
break
print("See the List", result)
Result:
Dictionery {'installerParameters': '', 'managedApp': {'_id': 'ChromeUnique', 'appId': 'ChromeID'}, 'postInstallAction': 0, 'postInstallScript': {'_id': '0'}, 'preInstallScript': {'_id': '0'}}
Dictionery {'installerParameters': '', 'managedApp': {'_id': 'FireFoxUnique', 'appId': 'FireFoxID'}, 'postInstallAction': 0, 'postInstallScript': {'_id': '0'}, 'preInstallScript': {'_id': '0'}}
See the List [{'installerParameters': '', 'managedApp': {'_id': 'FireFoxUnique', 'appId': 'FireFoxID'}, 'postInstallAction': 0, 'postInstallScript': {'_id': '0'}, 'preInstallScript': {'_id': '0'}}, {'installerParameters': '', 'managedApp': {'_id': 'FireFoxUnique', 'appId': 'FireFoxID'}, 'postInstallAction': 0, 'postInstallScript': {'_id': '0'}, 'preInstallScript': {'_id': '0'}}]
Define the dictionary in the for loop. You are currently writing to same dictionary object, and list holds reference to this object which itself is a reference. As a result you keep modifying the same object.
MyItems = ["ChromeSetup.exe","firefox.exe"]
listofitems = [{"appId": "ChromeID", 'id': "0","name": 'ChromeSetup.exe','_id': 'ChromeUnique'},{"appId": "FireFoxID", 'id': "0","name": 'firefox.exe','_id': 'FireFoxUnique'} ]
__id = ""
appId = ""
result = []
for app in MyItems:
for items in listofitems:
if items['name'] == app:
# I would try to find a better var name.
Dict = {"installerParameters":"","managedApp":{"_id":__id, "appId":appId},"postInstallAction":0,"postInstallScript":{"_id":"0"},"preInstallScript":{"_id":"0"}}
Dict["managedApp"]["_id"] = items['_id']
Dict["managedApp"]["appId"] = items['appId']
print("Dictionery",Dict)
result.append(Dict)
break
print("See the List", result)
Your dictionary object Dict is being overwritten during the second run of the loop. This is happening because you have defined the Dict above the loop. Better to define the Dict inside the loop.
I want to save an array of objects passed from javascript through ajax to me database. This is my view code:
data2 = json.loads(request.raw_get_data)
for i in data2:
print(key)
obj = ShoppingCart(quantity = i.quantity , user_id = 3, datetime = datetime.now(), product_id = i.pk)
obj.save()
return render_to_response("HTML.html",RequestContext(request))
After the first line, i get this in my dictionary:
[{'model': 'Phase_2.product', 'fields': {'name': 'Bata', 'category': 2, 'quantity': 1, 'subcategory': 1, 'count': 2, 'price': 50}, 'imageSource': None, 'pk': 1}]
(Only one object in the array right now)
I want to be able access individual fields like quantity, id, etc in order to save the data to my database. When i debug this code, it gives a name error on 'i'. I also tried accessing the fields like this: data2[0].quantity but it gives this error: {AttributeError}dict object has no attribute quantity.
Edited code:
for i in data2:
name = i["fields"]["name"]
obj = ShoppingCart(quantity = i["fields"]["quantity"] , user_id = 3, datetime = datetime.now(), product_id = i["fields"]["pk"])
obj.save()
It might help you to visualise the returned dict with proper formatting:
[
{
'model': 'Phase_2.product',
'fields': {
'name': 'Bata',
'category': 2,
'quantity': 1,
'subcategory': 1,
'count': 2,
'price': 50
},
'imageSource': None,
'pk': 1
}
]
The most likely reason for your error is that you are trying to access values of of the inner 'fields' dictionary as if they belong to the outer i dictionary.
i.e.
# Incorrect
i["quantity"]
# Gives KeyError
# Correct
i["fields"]["quantity"]
Edit
You have the same problem in your update:
# Incorrect
i["fields"]["pk"]
# Correct
i["pk"]
The "pk" field is in the outer dictionary, not the inner "fields" dictionary.
You may try:
i['fields']['quantity']
The json.loads() returns you a dictionary, which should be accessed by key.