I need to traverse through below nested dictionary and get the values highlighted "REM" and "signmeup-3.4.208.zip". Can anyone help in getting these values out?
{"actions":[{},{"parameters":[{"name":"ReleaseRequest","value":"REM"},{"name":"Artifact","value":"signmeup-3.4.2088.zip"}]},{"causes":[{"shortDescription":"Started by user ","userId":"sbc","userName":"xyz"}]},{},{},{},{},{},{"parameters":[{"name":"DESCRIPTION_SETTER_DESCRIPTION","value":"inf-xyz"}]},{}],"artifacts":[{"displayPath":"INT_backup.xml","fileName":"INT_backup.xml","relativePath":"INT_backup.xml"},{"displayPath":"Invalidlist.txt","fileName":"Invalidlist.txt","relativePath":"Invalidlist.txt"},{"displayPath":"OUT_backup.xml","fileName":"OUT_backup.xml","relativePath":"OUTP_backup.xml"}],"building":False,"description":"inf-ECR2.2088.zip","duration":1525074,"estimatedDuration":1303694,"executor":None,"fullDisplayName":"inf-#33","id":"2015-07-27_18-17-00","keepLog":False,"number":33,"result":"SUCCESS","timestamp":1438046220000,"url":"inf/33/","builtOn":"Windows_Slave","changeSet":{"items":[],"kind":None},"culprits":[]}
>>> d = {
... "actions": [
... {},
... {"parameters": [
... {"name": "ReleaseRequest", "value": "REM"},
... {"name": "Artifact", "value": "signmeup-3.4.208.zip"}
... ]},
... {"causes": [{"shortDescription": "user"}]}
... ]
... }
To get each value:
>>> d['actions'][1]['parameters'][0]['value']
'REM'
>>> d['actions'][1]['parameters'][1]['value']
'signmeup-3.4.208.zip'
To get all values:
>>> [param['value'] for param in d['actions'][1]['parameters']]
['REM', 'signmeup-3.4.208.zip']
Related
final List _icons = [
[
'IDENTITY',
FontAwesomeIcons.camera,
],
[
'SPECIES',
FontAwesomeIcons.tree,
],
[
'ARTICLES',
FontAwesomeIcons.bookOpen,
],
];
You can try
_icons[0][1] //FontAwesomeIcons.camera
but it seems like you can use a map instead of a list
final map _icons = { 'IDENTITY' : FontAwesomeIcons.camera, 'SPECIES': FontAwesomeIcons.tree, 'ARTICLES' : FontAwesomeIcons.bookOpen};
_icons['IDENTITY']; //FontAwesomeIcons.camera
In Terraform, I need to transform my input data structure from e.g.:
vip_lists = [
["1.0.1.1", "1.0.1.2", "1.0.1.3", "1.0.1.4"]
["1.0.2.1", "1.0.2.2", "1.0.2.3", "1.0.2.4"]
["1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4"]
]
to produce an output like this:
vip_sets = [
["1.0.1.1", "1.0.2.1", "1.0.0.1"]
["1.0.1.2", "1.0.2.2", "1.0.0.2"]
["1.0.1.3", "1.0.2.3", "1.0.0.3"]
["1.0.1.4", "1.0.2.4", "1.0.0.4"]
]
So essentially, i need to take my input list of lists and create an output which is again a list of lists but whose 0th list is a list of the 0th elements from each of the lists in the input...then the same again for the 1st and so on.
I can't know in advance how many lists will be in the input or how long they will be, but we can assume the lists will all be the same length if that helps.
I've tried pretty much everything I can think of and searched the web but since with no luck. All suggestions would be very welcome!
I once wrote version of this for lists of lists that are not the same length for one of our modules on github.com/mineiros-io where we used such transformations to create 2 dimensional sets of resources using count. (Those are not in use atm as we transformed them to maps for use with ressource level for_each).
locals {
matrix = [
["1.0.1.1", "1.0.1.4"],
["1.0.2.1", "1.0.2.2", "1.0.2.3", "1.0.2.4"],
["1.0.0.1", "1.0.0.3", "1.0.0.4"]
]
row_lengths = [
for row in local.matrix : length(row)
]
max_row_length = max(0, local.row_lengths...)
output = [
for i in range(0, local.max_row_length) : [
for j, _ in local.matrix : try(local.matrix[j][i], null)
]
]
output_compact = [
for i in range(0, local.max_row_length) : compact([
for j, _ in local.matrix : try(local.matrix[j][i], null)
])
]
}
output "matrix" {
value = local.output
}
output "compact" {
value = local.output_compact
}
which can handle dynamic list sizes and output them compact or filled with null values:
Outputs:
compact = [
[ "1.0.1.1", "1.0.2.1", "1.0.0.1" ],
[ "1.0.1.4", "1.0.2.2", "1.0.0.3" ],
[ "1.0.2.3", "1.0.0.4" ],
[ "1.0.2.4" ],
]
matrix = [
[ "1.0.1.1", "1.0.2.1", "1.0.0.1" ],
[ "1.0.1.4", "1.0.2.2", "1.0.0.3" ],
[ null, "1.0.2.3", "1.0.0.4" ],
[ null, "1.0.2.4", null ],
]
I know an answer is already accepted, but maybe some one can still make use of this dynamic version.
This is sort of horrible, but it works (Although I haven't tested what it'd do if vip_lists was empty. Probably crash, as I'm indexing to vip_lists[0] without checking):
locals {
vip_lists = [
["1.0.1.1", "1.0.1.2", "1.0.1.3", "1.0.1.4"],
["1.0.2.1", "1.0.2.2", "1.0.2.3", "1.0.2.4"],
["1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4"]
]
vip_sets = [for i in range(0, length(local.vip_lists[0])): [for j in range(0, length(local.vip_lists)): local.vip_lists[j][i]]]
}
output "vip_sets" {
value = local.vip_sets
}
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
vip_sets = [
[
"1.0.1.1",
"1.0.2.1",
"1.0.0.1",
],
[
"1.0.1.2",
"1.0.2.2",
"1.0.0.2",
],
[
"1.0.1.3",
"1.0.2.3",
"1.0.0.3",
],
[
"1.0.1.4",
"1.0.2.4",
"1.0.0.4",
],
]
I have the following ModelFactory:
class ProjectDataModelFactory(DjangoModelFactory):
project = factory.SubFactory("projects.factories.ProjectModelFactory")
version = "1"
content = {
"id": {"value": fuzzy.FuzzyText(length=7, chars=string.ascii_letters).fuzz().upper(), "type": "string"},
"win_probability": {"value": fuzzy.FuzzyInteger(0, 100).fuzz(), "type": "number"},
"bid_value": {
"value": fuzzy.FuzzyInteger(0, 10000000).fuzz(),
"type": "number",
},
"status": {"value": random.choice(["Won", "Lost"]), "type": "string"},
"sector": {
"value": random.choice(
["Construction", "Technology", "Finance", "Consulting", "Agriculture", "Engineering"]
),
"type": "string",
},
}
In content["id"], I would like to have value be project.external_id instead of fuzzy.FuzzyText(length=7, chars=string.ascii_letters).fuzz().upper(). external_idis part of the ProjectModel. But when I put project.external_id in the place of the fuzzer, I get this error:
AttributeError: 'SubFactory' object has no attribute 'external_id
This only seems to be a problem with dicts. We have not had issues using it in other contexts.
I do not have a lot of experience using FactoryBoy, so it could easily be something trivial. Any ideas?
You have a first issue: all the calls to random or .fuzz() that you put in the content dict are evaluated when the class is imported: each instance will use the exact same values.
In order to perform lazy evaluation, you MUST wrap them in some factory_boy-provided declaration:
class ProjectDataModelFactory(DjangoModelFactory):
project = factory.SubFactory("projects.factories.ProjectModelFactory")
version = "1"
content = factory.Dict(
id=factory.Dict(
value=fuzzy.FuzzyText(length=7, chars=string.ascii_uppercase),
type="string",
),
win_probability=factory.Dict(
value=fuzzy.FuzzyInteger(0, 100),
type="number",
),
bid_value=factory.Dict(
value=fuzzy.FuzzyInteger(0, 10_000_000),
type="number",
),
status=factory.Dict(
value=fuzzy.FuzzyChoice(["Won", "Lost"]),
type="string",
),
sector=factory.Dict(
value=fuzzy.FuzzyChoice(
["Construction", "Technology", "Finance", "Consulting", "Agriculture", "Engineering"],
),
type="string",
),
)
factory.Dict(**kwargs) is basically an alias for factory.SubFactory(DictFactory, **kwargs); you can then use any declaration as if using a simple SubFactory.
For your initial goal, you'll now be able to use all features easily:
class ProjectDataModelFactory(DjangoModelFactory):
project = factory.SubFactory("projects.factories.ProjectModelFactory")
version = "1"
content = factory.Dict(
id=factory.Dict(
# . is the {"value": x, "type": "string"} dict;
# .. is {"id": {"value": x, ...}} dict;
# ... is the ProjectData(content={"id": {...}}) object.
value=factory.SelfAttribute('...project.external_id'),
type="string",
),
# Other fields here
)
I have a json object contaning currencies as listed below which I need to convert it into my model and save it into the DB. Also is there a way to save the list of models in one go?
{
"results": {
"ALL": {
"currencyName": "Albanian Lek",
"currencySymbol": "Lek",
"id": "ALL"
},
"KWD": {
"currencyName": "Kuwaiti Dinar",
"id": "KWD"
},
"LSL": {
"currencyName": "Lesotho Loti",
"id": "LSL"
},
"MYR": {
"currencyName": "Malaysian Ringgit",
"currencySymbol": "RM",
"id": "MYR"
},
"MUR": {
"currencyName": "Mauritian Rupee",
"currencySymbol": "₨",
"id": "MUR"
}
}
}
I tried this :
for key,value in currencies.results :
#print(currency)
#print(value)
However, I get the following error :
"Too many attribures to unpack, expected 2
Can someone help me with this?
I think it should be like this:
results = currencies.get('results')
for key, value in results.items(): # for python3
print(key, value)
for key, value in results.iteritems(): # python2.7
print(key, value)
You should iterate as
for result in results:
for currency in result:
print(result)
I'm quite new to Python and programming in general, so apologies if this is quite basic or has been asked and answered before. Here is a sample of the data I'm working with:
{
"homeTeam": {
"formation": [
"4",
"4",
"2"
],
"lineupsSorted": [
{
"player": {
"name": "Scott P. Brown",
"slug": "scott-p-brown",
"shortName": "S. P. Brown",
"id": 19889,
"hasImage": true
},
"position": 1,
"shirtNumber": 1,
"substitute": false,
"positionName": "Goalkeeper",
"positionNameshort": "G",
"captain": false
},
{
"player": {
"name": "Carl Winchester",
"slug": "carl-winchester",
"shortName": "C. Winchester",
"id": 110785,
"hasImage": true
},
"position": 2,
"shirtNumber": 27,
"substitute": false,
"positionName": "Midfielder",
"positionNameshort": "M",
"captain": false
},
I am looking to automate populating defined names as I have done manually here:
hometeamPositions =['Goalkeeper','Midfielder','Defender','Defender','Defender','Midfielder','Midfielder','Midfielder','Midfielder','Forward','Forward','Goalkeeper','Defender','Defender','Midfielder','Midfielder','Forward','Forward']
hometeamPlayers = ['S. P. Brown','C. Winchester','M. Onariase','W.
Boyle','J. Cranston','H. Pell','J. Rowe','K. Storer','B. Waters','D.
Wright','D. Holman','R. Lovett','J. Barthram','T. Plavotic','J.
Munns','L. Davis','K. Wootton','J. Dayton']
As I will be repeating this process many hundreds of times with different data (same structure) I was wondering if anyone could give me some tips on automatically building these ranges?
Thanks,
Peter
I'm not sure I understood what is the problem you are trying to solve but I'll try to help.
Assuming you have a dictionary team_dict and you want to create 2 list: hometeamPositions and hometeamPlayers you can use the following code:
hometeamPlayers = []
hometeamPositions = []
for player_dict in teams_dict['homeTeam']['lineupsSorted']:
hometeamPlayers.append(player_dict['player']['shortName'])
hometeamPositions.append(player_dict['positionName'])
The output on your example will be:
hometeamPlayers = ['S. P. Brown', 'C. Winchester']
hometeamPositions = ['Goalkeeper', 'Midfielder']