I am creating unique collections from every column in my sheet under the column headings using dictionary object. Column headings are in Row 1.
Problem is my dictionaries contains unique items from previous columns. for example if call a dictionary of column 4, it contains all unique items and headings from columns 1,2,3. I need only unique items from that perticular column. Any idea how to correct this code?.
Sub cre_Dict()
Dim fulArr As Variant
Set d = CreateObject("scripting.dictionary")
With Sheets("Database")
fulArr = .Range("A1:IO27") 'assign whole table to array
For j = 1 To UBound(fulArr, 2) 'looping from 1st column to last column
For i = 2 To UBound(fulArr, 1) 'looping from row2 to last row
If Len(fulArr(i, j)) > 0 Then 'if not blank cell
d00 = d.Item(fulArr(i, j)) 'add to dictionary
End If
Next i
d(fulArr(1, j)) = d.keys 'create dictionary under column heading
Next j
End With
End Sub
Thanks
asked Nov 19, 2015 at 15:11
ShanShan
4193 gold badges14 silver badges30 bronze badges
7
Consider the below example, based on your code with minor changes I have made:
Dim d As Object
Sub cre_Dict()
Dim fulArr As Variant
Dim q As Object
Dim j As Long
Dim i As Long
Set d = CreateObject("Scripting.Dictionary")
fulArr = Sheets("Database").Range("A1:IO27") 'assign whole table to array
For j = 1 To UBound(fulArr, 2) 'looping from 1st column to last column
Set q = CreateObject("Scripting.Dictionary")
For i = 2 To UBound(fulArr, 1) 'looping from row2 to last row
If Len(fulArr(i, j)) > 0 Then 'if not blank cell
q(fulArr(i, j)) = Empty 'add to dictionary
End If
Next i
d(fulArr(1, j)) = q.Keys 'create dictionary under column heading
Next j
End Sub
answered Nov 19, 2015 at 16:32
omegastripesomegastripes
12.3k4 gold badges44 silver badges95 bronze badges
0
If I’ve got this correct, you have duplicates in different columns. So basically your keys in the dictionary are not unique as you iterate over columns. If that’s the case, when you add your keys to the dictionary, create a composite key. For example something like:
Dim sKey as string
sKey = «A~» & «ABCD»
This will then make the key unique for column A.
When processing the collection, you can strip out the «A~» part for each column.
answered Nov 19, 2015 at 15:59
PaulGPaulG
1,0217 silver badges9 bronze badges
-
#1
Hi all, apologies in advance if there is a solution to this somewhere — I have been unable to find it either on these boards or the internet at large.
I am trying to create a dictionary (Dictionary object in reference Microsoft Scripting Runtime) where the values to the keys are themselves dictionaries. I have a loop which populates the sub-dictionary, writes the sub-dictionary to the main dictionary, then goes back generates a new sub-dictionary writes it back, etcetera. What I get is a dictionary with the correct keys, but all the values are identical dictionaries (the last one to be added). I guess that the sub-dictionary is being added to the main dictionary by reference, so when the loop goes to create the next one it’s overwriting all previous keys too.
This code replicates my problem:
Code:
' output:
'First dictionary,First dictionary,1
'-----
'First dictionary,Second dictionary,2
'Second dictionary,Second dictionary,2
Function test()
Dim d As New Dictionary
Dim e As New Dictionary
e.Add "Key1", "First dictionary"
e.Add "Key2", "1"
d.Add e("Key1"), e
For i = 0 To d.Count - 1
Debug.Print d.keys(i) & "," & d.Items(i).Item("Key1") & "," & d.Items(i).Item("Key2")
Next
Debug.Print "-----"
e.RemoveAll
e.Add "Key1", "Second dictionary"
e.Add "Key2", "2"
d.Add e("Key1"), e
For i = 0 To d.Count - 1
Debug.Print d.keys(i) & "," & d.Items(i).Item("Key1") & "," & d.Items(i).Item("Key2")
Next
End Function
…and this seems to overcome the problem but perhaps there’s a better solution?
Code:
Function addict(dict As Dictionary, subdict As Dictionary, k As String) As Dictionary
dict.Add k, New Dictionary
For i = 0 To subdict.Count - 1
dict.Item(k).Add subdict.keys(i), subdict.Items(i)
Next
Set addict = dict
End Function
' output:
'First dictionary,First dictionary,1
'-----
'First dictionary,First dictionary,1
'Second dictionary,Second dictionary,2
Function test2()
Dim d As New Dictionary
Dim e As New Dictionary
e.Add "Key1", "First dictionary"
e.Add "Key2", "1"
Set d = addict(d, e, e("Key1"))
For i = 0 To d.Count - 1
Debug.Print d.keys(i) & "," & d.Items(i).Item("Key1") & "," & d.Items(i).Item("Key2")
Next
Debug.Print "-----"
e.RemoveAll
e.Add "Key1", "Second dictionary"
e.Add "Key2", "2"
Set d = addict(d, e, e("Key1"))
For i = 0 To d.Count - 1
Debug.Print d.keys(i) & "," & d.Items(i).Item("Key1") & "," & d.Items(i).Item("Key2")
Next
End Function
Perhaps this is the wrong approach entirely — it grew out of a dictionary of collections, and I decided to recode the collections in favour of dictionaries for ease of use.
What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.
-
#2
Perhaps if you explain, in words, what you are trying to achieve somebody might be able to tell you if this is the right/wrong approach.
And if it is the wrong approach then perhaps another one can be suggested.
PS Why are you using Function?
Function is normally used when you want to return a value, and the code you’ve posted isn’t doing that.
-
#3
Essentially I’m parsing a table from an external source and I want to be able to access the data in it in a relatively straightforward fashion. The table contains unique field which I use to generate the keys of the main dictionary, and then using a sub-dictionary lets me access a property of the record knowing its name. I don’t just want to put it in a 2D array because finding property( record ) is cumbersome.
Is there a better way?
-
#4
The items of dictionary could be string,numbers,array or object.
Use dictionary+array to solve your question,have a glance at the following code,maybe it helps you:
Code:
Sub macro1()
Dim arr, i As Long, j As Long, dic As Object
Set dic = CreateObject("scripting.dictionary")
For i = 2 To 100
ReDim arr(1 To i)
For j = 1 To i
arr(j) = j
Next
dic("d" & i) = arr
Next
i = Int(Rnd * 99 + 1)
MsgBox Join(dic("d" & i), ","), , "dic(""d" & i & """)"
End Sub
Regards
Northwolves
-
#5
Hi all, apologies in advance if there is a solution to this somewhere — I have been unable to find it either on these boards or the internet at large.
I am trying to create a dictionary (Dictionary object in reference Microsoft Scripting Runtime) where the values to the keys are themselves dictionaries. I have a loop which populates the sub-dictionary, writes the sub-dictionary to the main dictionary, then goes back generates a new sub-dictionary writes it back, etcetera. What I get is a dictionary with the correct keys, but all the values are identical dictionaries (the last one to be added). I guess that the sub-dictionary is being added to the main dictionary by reference, so when the loop goes to create the next one it’s overwriting all previous keys too.
This code replicates my problem:
Code:
' output: 'First dictionary,First dictionary,1 '----- 'First dictionary,Second dictionary,2 'Second dictionary,Second dictionary,2 Function test() Dim d As New Dictionary Dim e As New Dictionary e.Add "Key1", "First dictionary" e.Add "Key2", "1" d.Add e("Key1"), e For i = 0 To d.Count - 1 Debug.Print d.keys(i) & "," & d.Items(i).Item("Key1") & "," & d.Items(i).Item("Key2") Next Debug.Print "-----" e.RemoveAll e.Add "Key1", "Second dictionary" e.Add "Key2", "2" d.Add e("Key1"), e For i = 0 To d.Count - 1 Debug.Print d.keys(i) & "," & d.Items(i).Item("Key1") & "," & d.Items(i).Item("Key2") Next End Function
…and this seems to overcome the problem but perhaps there’s a better solution?
Code:
Function addict(dict As Dictionary, subdict As Dictionary, k As String) As Dictionary dict.Add k, New Dictionary For i = 0 To subdict.Count - 1 dict.Item(k).Add subdict.keys(i), subdict.Items(i) Next Set addict = dict End Function ' output: 'First dictionary,First dictionary,1 '----- 'First dictionary,First dictionary,1 'Second dictionary,Second dictionary,2 Function test2() Dim d As New Dictionary Dim e As New Dictionary e.Add "Key1", "First dictionary" e.Add "Key2", "1" Set d = addict(d, e, e("Key1")) For i = 0 To d.Count - 1 Debug.Print d.keys(i) & "," & d.Items(i).Item("Key1") & "," & d.Items(i).Item("Key2") Next Debug.Print "-----" e.RemoveAll e.Add "Key1", "Second dictionary" e.Add "Key2", "2" Set d = addict(d, e, e("Key1")) For i = 0 To d.Count - 1 Debug.Print d.keys(i) & "," & d.Items(i).Item("Key1") & "," & d.Items(i).Item("Key2") Next End Function
Perhaps this is the wrong approach entirely — it grew out of a dictionary of collections, and I decided to recode the collections in favour of dictionaries for ease of use.
You’ve probably completed your project by now, but all you really needed to do was change
to
-
#6
You’ve probably completed your project by now, but all you really needed to do was change
to
Hello MattJK,
I’m so thankful for that moment when you decided to post this even if probably the author has already solved it because you helped me to solve this same issue that I was facing for days… I knew that dictionaries store information differently than arrays, but I didn’t figure out how to use them as arrays and preserve the dynamics of the dictionaries until I found your answer.
I signed in to the forum just to let you know that and to thank you so much.
Probably I will come back to post my code and see if someone can suggest me a way to optimize it.
Have a nice day, mate.
-
Solved
Василий Пользователь Сообщений: 29 |
Коллеги, Подскажите, есть ли возможность добавления словаря в качестве значения в другой словарь? К примеру есть основной словарь: ГЛ_СЛОВАРЬ (Ключ1: Значение1; Ключ2 : Значение2; …) Вместо Значение1, Значение2, … должны быть словари. В итоге хотелось бы увидеть следующее: ГЛ_СЛОВАРЬ (Ключ1: ВЛ_СЛОВАРЬ(Ключ1_1: Значение 1, …); Ключ2 : ВЛ_СЛОВАРЬ(Ключ2_2: Значение 1, …); …) Если есть такая возможность, то каким образом можно заполнить такую структуру и как к ней обращаться? |
что мешает? добавляйте Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
|
Василий Пользователь Сообщений: 29 |
#3 27.04.2022 07:23:10 Примерно получается такой кусочек кода, но он не рабочий:
|
||
Василий Пользователь Сообщений: 29 |
Т.е. я не совсем понимаю, как правильно вложить словарь во внутрь и как его при необходимости оттуда взять… |
но вы хоть понимаете что вы хотите вложить в словари? Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
|
Jack Famous Пользователь Сообщений: 10848 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
Василий, файл с кодом и данными Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
Бахтиёр Пользователь Сообщений: 1930 Excel 365 |
#7 27.04.2022 09:46:26
Прикрепленные файлы
Изменено: Бахтиёр — 27.04.2022 09:47:16 |
||
Jack Famous Пользователь Сообщений: 10848 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
Ну раз решение есть, то добавлю, что иногда может быть удобнее использовать массив словарей aDic() As Dictionary Изменено: Jack Famous — 27.04.2022 10:20:37 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
Василий Пользователь Сообщений: 29 |
#9 27.04.2022 14:20:16 Коллеги, Спасибо за Ваш труд. В итоге остановился на варианте, который я описал в самом начале. Меня интересовало как именно в словарь, в значение его ключа включить еще один словарь. Почему не массив, потому что со словарем проще работать, там не нужно делать циклы для перебора значений. Оказалось, что код, который я написал не корректно работал из-за разницы в типах данных.
Так вот, проблема была в том, что значение ключа в словарь нужно было вставлять, предварительно преобразовав его в текстовый формат. После этого все завелось |
||
New Пользователь Сообщений: 4581 |
#10 27.04.2022 20:34:44
— скажите любое слово из русского языка? Изменено: New — 27.04.2022 23:25:37 |
||
Василий Пользователь Сообщений: 29 |
New, А Вы просто флудите. |
Msi2102 Пользователь Сообщений: 3137 |
#12 28.04.2022 07:12:58
Ну давайте начнём с того, что заморочиться должны были Вы, а не помогающий. Вы правила форума для начала почитайте и подумайте, почему у вас так мало ответов с решениями. И вообще удивительно, что эта тема просуществовала так долго. С таким названием, модераторы, как правило их удаляют.
Оно конечно может подходить, но в данной ветке должен быть поставлен конкретный вопрос, что именно не получается, и это также должно быть отражно в названии темы (что кстати тоже описано в правилах форума и модераторы за этим строго следят) , а не задавать филосовские вопросы, о проблемах словаря в словаре. |
||||
БМВ Модератор Сообщений: 21378 Excel 2013, 2016 |
Все остановились! По вопросам из тем форума, личку не читаю. |
Jack Famous Пользователь Сообщений: 10848 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
Msi2102, пусть сидит теперь и ждёт помогающих, которые всё за него сделают Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
Александр Моторин Пользователь Сообщений: 958 |
#15 02.05.2022 08:06:03
кусок кода из моей программы |
||
02-25-2014, 06:18 PM
#1
Registered User
Creating Dictionary of Dictionaries
Hi Everybody!
I’m new here and new with VBA as well. I’m trying to create a Dictionary of Dictionaries with the following code:
Dim dic As Dictionary, e, s
Set dic = New Dictionary ‘<- main dictionary
Set dic(a) = New Dictionarywhere dic(a) stands for 100 baby dictionaries that I’m trying to fill by looping the variable a from 1 to 100. It turns out to be not feasible. Do I have to Set all dic(1), dic(2), dic(3)…dic(100) individually which works? Since using a variable for those baby ones would be extremely easy for downstream analysis, I’d really appreciate it if someone could help on this.
Thanks in advance.
02-25-2014, 07:12 PM
#2
Re: Creating Dictionary of Dictionaries
Why would you want a dictionary of dictionaries, as opposed to a collection of dictionaries?
Last edited by shg; 02-25-2014 at 07:22 PM.
Entia non sunt multiplicanda sine necessitate
02-25-2014, 09:40 PM
#3
Re: Creating Dictionary of Dictionaries
for child dictionaries within a parent dictionary
not clear what purpose a collection would serve in this context that a dictionary doesn’t
02-26-2014, 12:22 AM
#4
Registered User
Re: Creating Dictionary of Dictionaries
Thanks a lot shg! I got more sense about the keys of the baby dictionaries.
Why use a dictionary of dictionaries, instead of collection of dictionaries? Just based on what I know so far. By reading about this topic, I learned that a dictionary has many advantages and convenience over a collection. However, it is the first time for me to use dictionary. I really don’t know the difference when they have babies. Would you think a collection of dictionaries is better?
02-26-2014, 12:34 AM
#5
Registered User
Re: Creating Dictionary of Dictionaries
Great Kalak! This makes the layers clear. Thanks a lot. Would you recommend something to read about dictionary of dictionaries? I could not see much online. My next step is to identify similarities among the items in these baby dictionaries and have not really figured out what would be the best way to do it. Any suggestions?
02-26-2014, 01:01 AM
#6
Re: Creating Dictionary of Dictionaries
Would you think a collection of dictionaries is better?
You can access a collection by index; a dictionary only by key.
02-26-2014, 01:26 AM
#7
Re: Creating Dictionary of Dictionaries
Originally Posted by Dodo123
… Would you recommend something to read about dictionary of dictionaries? I could not see much online. My next step is to identify similarities among the items in these baby dictionaries and have not really figured out what would be the best way to do it. Any suggestions?
There’s not that much that I know of, although in general a dictionary of dictionaries shouldn’t be too different from a dictionary of anything else. Also, the fact that you raised the topic implies you must have some idea of just why you did so.
For more information, there’s a good summary of dictionaries by snb here http://www.snb-vba.eu/VBA_Dictionary_en.html , which also has something to say about indexes and keys.
It’s unclear just what you mean by
«… identify similarities among the items in these baby dictionaries …»
What kind of similarities?
Could you be more specific?
Example perhaps?
02-26-2014, 10:30 AM
#8
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by shg
You can access a collection by index; a dictionary only by key.
Thanks again. I’ll look into it.
02-26-2014, 11:14 AM
#9
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by kalak
There’s not that much that I know of, although in general a dictionary of dictionaries shouldn’t be too different from a dictionary of anything else. Also, the fact that you raised the topic implies you must have some idea of just why you did so.
For more information, there’s a good summary of dictionaries by snb here http://www.snb-vba.eu/VBA_Dictionary_en.html , which also has something to say about indexes and keys.
It’s unclear just what you mean by
«… identify similarities among the items in these baby dictionaries …»
What kind of similarities?
Could you be more specific?
Example perhaps?Thanks for the link. I actually went over about half of the content yesterday and checked the topics of the other half. It is a very comprehensive summary and very useful. Unfortunately, no direct info about dictionary of dictionaries. Probably I may refer the way they use to handle dictionary of arrays.
Sorry about the confusion caused by my description about my next step. It is a research project. What I need is to:
1. Store all data into dictionaries one a data set.
2. Compare between each pair of the dictionaries to identify identical items (and different items as well) using something like the MATCH function in Excel (suggestion of a better method?)
3. Split the items in each of the two dictionaries into two groups (identical ones and different ones between the two dictionaries). I will need to store the groups into new baby dictionaries.
4. Compare items in each with those in the remaining 99 dictionaries and to further split the groups.
5. All 100 data sets need to be analyzed in this way. Therefore, the number of combinations will be huge (any better idea than combination?).
6. The final groups should be undividable—indicating that items in each of these final groups co-exist in the nature.
Note: the Items in each data set are a part of a big data set. Items co-exist in the nature have less chance to be divided into different subsets.
Hope this is clear
Last edited by Dodo123; 02-28-2014 at 02:06 AM.
02-26-2014, 11:15 AM
#10
Registered User
Re: Creating Dictionary of Dictionaries
Reiterative post — content was removed
02-26-2014, 11:18 AM
#11
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by shg
You can access a collection by index; a dictionary only by key.
Please take a look at #9. Your suggestions are appreciated.
02-26-2014, 11:18 AM
#12
Re: Creating Dictionary of Dictionaries
You describe the steps of an algorithm. More generally, what are you trying to do?
It seems there should be a much easier way.
Last edited by shg; 02-26-2014 at 11:21 AM.
02-26-2014, 01:03 PM
#13
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by shg
You describe the steps of an algorithm. More generally, what are you trying to do?
It seems there should be a much easier way.
It is something like this: I have 10 rulers of 1000 cm, all labeled by 1001 distinct letters in a given order but not alphabetic, 1 cm/letter. That means you won’t be able to figure out the order of the letters by simply reading the letters. However, the letters are in the same order for all 10 rulers.
I chop each ruler into 100 segments at random points and mix the 100 segments together. I have a way to identify the letters in each mixture (not on the segments). After analyzing each mixture, I only know there are 1001 letters in it and won’t be able to know the order of the letters.
Now, if I divide the 100 segments into 10 subgroups for each of the 10 rulers. After identifying the letters in each subgroups, I should be able to recover the original order of the letters based on the fact that adjacent letters tend to «travel» together in the subgroups and based on the information of overlapping segments from different rulers (Note, no overlapping segments can be generated from the same ruler).
Interesting? Look forward to your suggestions.
02-26-2014, 01:20 PM
#14
Re: Creating Dictionary of Dictionaries
Some kind of DNA alignment thing?
02-26-2014, 02:16 PM
#15
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by shg
Some kind of DNA alignment thing?
Haha, similar. Any suggestions?
02-26-2014, 03:58 PM
#16
Re: Creating Dictionary of Dictionaries
What does the source data look like? What does the output look like?
02-27-2014, 12:29 PM
#17
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by shg
What does the source data look like? What does the output look like?
Hi shg,
Sorry about replying you late. I didn’t notice this 2nd page. The source data looks like these (only 6 subgroups from two rulers are shown):
Data.JPG
Where each R+3 digit number represents the number in the real order. ID is the «letters» on the ruler, but numbers are used instead here . Although the ID’s are sorted based on their numeric values, they don’t implicate anything about the real order of the «letters.» G: subgroup; and «+»: present.
I don’t have a clear idea about the output format yet. It would be ideal if the output looks like these:
Result.JPG
You can see now, although the real order has not been recovered, the «letters» are grouped into segments with adjacent «letters» grouped together. Eventually, we should be able to deduce the order of the letters like this, in which the real order is recovered:
Result2.JPG
I tried to paste the tables in text in case you want to play with them. However the format can’t be kept. So, they are all in images.
Last edited by Dodo123; 02-27-2014 at 12:39 PM.
Reason: format of tables cannot be kept
02-27-2014, 12:43 PM
#18
Re: Creating Dictionary of Dictionaries
You can post a workbook.
Are those two examples side by side in each case, or two parts of a single example?
02-27-2014, 02:54 PM
#19
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by shg
You can post a workbook.
Are those two examples side by side in each case, or two parts of a single example?
These are two samples side by side. I tried to post a workbook but could not find how. Now I know. Here we go (in Excel 2013)!
02-27-2014, 03:16 PM
#20
Re: Creating Dictionary of Dictionaries
Is that two examples or one? If it’s two, please get rid of one, and show the steps that transmute one set of inputs to one output.
Then I’ll ask the logic applied at each step.
Please consider that only one of us has any clue of what you have or are trying to do.
Last edited by shg; 02-27-2014 at 03:29 PM.
02-27-2014, 05:04 PM
#21
Registered User
Re: Creating Dictionary of Dictionaries
Those are two SAMPLES in one EXAMPLE. Remember, we have 10 rulers (two are shown in the spread sheet) each was chopped at random points into 100 segments. The 100 segments are mixed first and then subdivided into 10 subgroups (6 (columns) are shown here. There are should be an average of 10 segments in each subgroup. Only one segment in each group is shown in the sheet. The steps to transmute the input information to output would include the follows:
1. Ordinarily, we may take a pair of «letters» (say 121 and 123) identified from the same subgroup (a column in the worksheet) and then ask if they are co-present among the subgroups from other nine rulers. If their co-present rate is significantly greater than the expected based on random combination, they are considered to be from the same segment, and otherwise, from different segments.
2. After exhausting all pairwise tests, letters of the same segment origin can be identified and sorted into segment-like form like what you see in the left two panels in the 2nd sheet, «Output & Final.»
Note: The number of pairwise combinations is large. There should be method(s) similar to or better than the MATCH function that does not require pairwise test.
3. Run the same test for all subgroups from all 10 rulers so that letters in each group can be grouped based on their segment origins. At this point, you can only subdivide the letters based on their segment origins and don’t know the order of the segments.
4. Work out the order of the overlapping «segments,» for example
12 24 56 6 from one subgroup of ruler 1 and 56 6 897 25 from a subgroup of ruler 5 can be used to assemble the order of
12 24 56 6 897 254 based their overlapping letters of 56 and 6.
5. Extend the segment assembly until the entire order of the letters are worked out along the length of the entire ruler.
These steps are what I can imagine. There might be modifications as the programming goes.
02-27-2014, 09:28 PM
#22
Re: Creating Dictionary of Dictionaries
Those are two SAMPLES in one EXAMPLE. Remember, we have 10 rulers (two are shown in the spread sheet) each was chopped at random points into 100 segments. The 100 segments are mixed first and then subdivided into 10 subgroups (6 (columns) are shown here. [shg] On what basis are they assigned to subgroups? The + in the column is the subgroup assignment?Why are the column orders different in the two samples?
There are should be an average of 10 segments in each subgroup. Only one segment in each group is shown in the sheet. The steps to transmute the input information to output would include the follows:
1. Ordinarily, we may take a pair of «letters» (say 121 and 123) identified from the same subgroup (a column in the worksheet) and then ask if they are co-present among the subgroups from other nine rulers. If their co-present rate is significantly greater than the expected based on random combination, they are considered to be from the same segment, and otherwise, from different segments.
[shg] Where do you see «121» or «123»? You mean the ID column? Are the IDs the same on all rulers?
2. After exhausting all pairwise tests, letters of the same segment origin can be identified and sorted into segment-like form like what you see in the left two panels in the 2nd sheet, «Output & Final.»
Note: The number of pairwise combinations is large. There should be method(s) similar to or better than the MATCH function that does not require pairwise test.
3. Run the same test for all subgroups from all 10 rulers so that letters in each group can be grouped based on their segment origins. At this point, you can only subdivide the letters based on their segment origins and don’t know the order of the segments.
4. Work out the order of the overlapping «segments,» for example
12 24 56 6 from one subgroup of ruler 1 and 56 6 897 25 from a subgroup of ruler 5 can be used to assemble the order of
12 24 56 6 897 254 based their overlapping letters of 56 and 6.
[shg] Where does 12 24 56 6 appear in a subgroup of ruler 1?
5. Extend the segment assembly until the entire order of the letters are worked out along the length of the entire ruler.
These steps are what I can imagine. There might be modifications as the programming goes.
[shg] I fear I am at sea. What’s the genesis of the problem?
Last edited by shg; 02-27-2014 at 09:32 PM.
02-28-2014, 01:06 AM
#23
Registered User
Re: Creating Dictionary of Dictionaries
Those are two SAMPLES in one EXAMPLE. Remember, we have 10 rulers (two are shown in the spread sheet) each was chopped at random points into 100 segments. The 100 segments are mixed first and then subdivided into 10 subgroups (6 (columns) are shown here.) [shg] On what basis are they assigned to subgroups? The + in the column is the subgroup assignment?Why are the column orders different in the two samples?They are just randomly distributed into subgroups. As mentioned in the previous post, the reason for doing so is for the association test since closely located letters are tend to be distributed into the same subgroup. The + sign means «present». As show in the table on the left side, in the G1 column, 5, 10, 12, 45, 51, 54 and 982 are present while others are not. I shuffled the column order in the table on the right just want to indicate that the order of the column are irrelevant to the issue and does not provide any information for solving the problem.
There are should be an average of 10 segments in each subgroup. Only one segment in each group is shown in the sheet. The steps to transmute the input information to output would include the follows:
1. Ordinarily, we may take a pair of «letters» (say 121 and 123) identified from the same subgroup (a column in the worksheet) and then ask if they are co-present among the subgroups from other nine rulers. If their co-present rate is significantly greater than the expected based on random combination, they are considered to be from the same segment, and otherwise, from different segments.
[shg] Where do you see «121» or «123»? You mean the ID column? Are the IDs the same on all rulers?Sorry about not taking the actual «letters» (IDs) from the tables. «121» and «123» were just examples. Yes, IDs are the same and in the same order on all rulers.
2. After exhausting all pairwise tests, letters of the same segment origin can be identified and sorted into segment-like form like what you see in the left two panels in the 2nd sheet, «Output & Final.»
Note: The number of pairwise combinations is large. There should be method(s) similar to or better than the MATCH function that does not require pairwise test.
3. Run the same test for all subgroups from all 10 rulers so that letters in each group can be grouped based on their segment origins. At this point, you can only subdivide the letters based on their segment origins and don’t know the order of the segments.
4. Work out the order of the overlapping «segments,» for example
12 24 56 6 from one subgroup of ruler 1 and 56 6 897 25 from a subgroup of ruler 5 can be used to assemble the order of
12 24 56 6 897 254 based their overlapping letters of 56 and 6.
[shg] Where does 12 24 56 6 appear in a subgroup of ruler 1?
Sorry again, these are just examples, not taken from the actual subgroups in the table.Let’s work with the information from the tables in Sheet «Output & Final,»
In the left table,
G4 column has 218 7845 21 68 132 651 284 3 108
In the right table,
G5 column has 284 3 108 84 121Sharing 284 3 108 by the two subgroups allows deduction of an order of
218 7845 21 68 132 651 284 3 108 84 121
5. Extend the segment assembly until the entire order of the letters are worked out along the length of the entire ruler.
These steps are what I can imagine. There might be modifications as the programming goes.
[shg] I fear I am at sea. What’s the genesis of the problem? It is a rather complex problem. It took me a while to figure out how to explain to you. The example that I give to you was a lot simplified from the actual data. However, it does present one of the core issues that I’m working on. If you read what I have described so far from the very beginning, you may start to get some sense about the issue. I’ll be happy to answer more questions if you have
Last edited by Dodo123; 02-28-2014 at 01:08 AM.
02-28-2014, 01:16 AM
#24
Re: Creating Dictionary of Dictionaries
I reckon I feel that it’s a complicated problem, and have no sense of the merit or value in trying to solve it, given a very abstract problem statement and no sense of what it all means.
02-28-2014, 01:58 AM
#25
Registered User
Re: Creating Dictionary of Dictionaries
I don’t think the description is very abstract. The issue is straightforward and clear — to figure out the order of the markers on a ruler that has been chopped into pieces. Only are markers within the same piece prevented from separation into different subgroups. Obviously, you may not be able to solve the problem with only one ruler. With 10 rulers having randomly generated pieces, you should be able to. I’m done my best to explain every point with an example. However, if you pursue the merit or value, that is something else, beyond the issue itself.
Anyway, thanks a lot for your patience.
02-28-2014, 02:47 AM
#26
Re: Creating Dictionary of Dictionaries
Hi Dodo123,
maybe something like this (for B2:I38 range on Data worksheet)
02-28-2014, 10:48 AM
#27
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by nilem
Hi Dodo123,
maybe something like this (for B2:I38 range on Data worksheet)Hi nilem,
Thanks so much for the help. I’ve seen your post and digesting. I’ll get back to you with my thought after comprehend your sub (I’m new with VBA :-)). Have a nice evening there if I need more time before your bedtime.
02-28-2014, 06:45 PM
#28
Registered User
Re: Creating Dictionary of Dictionaries
Good morning nilem.
Thanks for your code that provides an interesting way to sort the markers «+» into an order.
However, the marker order has to be determined by their co-presence in the subgroups from all the 10 rulers. In this way, the IDs in the «Real Order» column can be sorted into clusters with neighboring markers in the same cluster. As shown in the 2nd sheet, markers in G1 are clustered with their real order IDs, R013 R014 R015 R016 R017 R018 R019. This indicates the success of computation.
Please note, there are should 100 segments for each column and only one is shown in the tables.
03-01-2014, 01:02 AM
#29
Registered User
Re: Creating Dictionary of Dictionaries
To all who have gone over this thread,
If you are interested in solving this issue, but don’t have time to work out the code, carefully going over the posts and provide algorithmic suggestions would be appreciated. Suggestions could include the effective way to storing a large number of data sets, handling a large number of comparisons point by point, scoring the number of subgroups in which a given pair of markers are present(I called «markers» as «letters» in the previous posts), etc.
Many thanks to those who have offered help so far regardless how much you dug into it. I know it is a very challenging issue, yet very interesting.
03-01-2014, 01:33 AM
#30
Re: Creating Dictionary of Dictionaries
Originally Posted by Dodo123
…there are should 100 segments for each column and only one is shown in the tables.
Could you show an example with more than one segment (at least 2 or 3) in the «before and after» mode
03-01-2014, 07:04 PM
#31
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by nilem
Could you show an example with more than one segment (at least 2 or 3) in the «before and after» mode
Sorry about replying you late. It took me a while to generate what you requested. Please see the two attached workbooks.
Sheet1 in the two books are identical. It contains the actual order of the markers on the rulers represented by numbers with a prefix of «R» in Column «Real Order.» The numbers in the «ID» column are the IDs assign to the markers when the real order is unknown. «+» means «Presence.»
Each of Sheets 2 to 7 in Data Example Set2a contains raw data for one of six rulers. Each ruler is chopped into ~20 segments which are randomly distributed into 10 subgroups, two each (occasionally three). Marker IDs are identified from each subgroup and indicated by a «+» sign. For a given ruler, all IDs are unique. IDs for the same position on all rulers are the same. In this book, IDs are sorted based on their numeric values. However, this does not provided any information about the actual order of the markers on the rulers. At this point, the «Real Order» is unknown.
Data Example Set2b contains clustered markers assuming the «Real Order» is worked out and the markers are sorted based on the real order.
If you have any questions, please let me know.
Thanks a lot!
03-02-2014, 01:54 AM
#32
Re: Creating Dictionary of Dictionaries
Hi Dodo123,
I just sort tables by the 1st column in a «Set2a» file and got exactly the same tables as in the «Set2b» file. And I see no reason to use a dictionary or a dictionary of dictionaries to get this result. Sorry.
03-02-2014, 11:30 AM
#33
Registered User
Re: Creating Dictionary of Dictionaries
Originally Posted by nilem
Hi Dodo123,
I just sort tables by the 1st column in a «Set2a» file and got exactly the same tables as in the «Set2b» file. And I see no reason to use a dictionary or a dictionary of dictionaries to get this result. Sorry.Again, the 1st column is used to validate your results. It should be taken out and cannot be used to sort as it does not exist in the real data. You need to use logic association of the markers in the segments rather than using a pure algorithmic method to get the order, since this is not a magic cube.
Last edited by Dodo123; 03-03-2014 at 01:55 PM.
6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
|
1 |
|
словарь словарей30.03.2017, 00:58. Показов 13672. Ответов 30
Здравствуйте.
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
30.03.2017, 00:58 |
30 |
Alex77755 11482 / 3773 / 677 Регистрация: 13.02.2009 Сообщений: 11,145 |
||||||||
30.03.2017, 02:15 |
2 |
|||||||
Сообщение было отмечено kronos_o_0 как решение Решение
Добавлено через 58 секунд Добавлено через 1 минуту
1 |
Hugo121 6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
||||
30.03.2017, 08:43 |
3 |
|||
Сообщение было отмечено kronos_o_0 как решение РешениеЯ так делал в другой задаче:
1 |
kronos_o_0 6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
||||
30.03.2017, 09:32 [ТС] |
4 |
|||
Alex77755, я пытался сделать на подобие первого, но не совсем понял, там второй словарь вкладывают в коллекцию?
.Item(t).Item(a(i, 2) & «|» & a(i, 3) & «|» & i) = 0& вот что у меня получилось, но я не могу обратится к Dic через .item
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
30.03.2017, 09:46 |
5 |
У меня на итем не ругается, да и у Вас скорее всего ругается на выход за пределы массива.
0 |
kronos_o_0 6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
||||
30.03.2017, 09:50 [ТС] |
6 |
|||
вставил эту часть, показало что словарь заполнен ключ[ключ, но итем второго словаря пуст]
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
30.03.2017, 10:00 |
7 |
как проверить заполненность словаря-словарей тут что пишет?
Debug.Print «Ищем данные » & col
0 |
6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
|
30.03.2017, 10:07 [ТС] |
8 |
тут что пишет? Открываем файл литий
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
30.03.2017, 10:13 |
9 |
Ну так вот же — у лития в словаре 1, 2 и 8, у аммония 2, 1, 6 и т.д. Добавлено через 2 минуты
0 |
6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
|
30.03.2017, 10:13 [ТС] |
10 |
Ну так вот же — у лития в словаре 1, 2 и 8, у аммония 2, 1, 6 и т.д. да тут все правильно, но нет значений у 1,2,8 и т.д., у них должны быть еще
0 |
Hugo121 6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
||||
30.03.2017, 10:27 |
11 |
|||
Да, в той реализации у всех внутренних значение 0, но можно изменить как угодно, а вывести можно если убрать апостроф в строке
0 |
6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
|
30.03.2017, 10:35 [ТС] |
12 |
Hugo121, Спасибо большое, действительно все работало
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
30.03.2017, 10:51 |
13 |
Да, по тому же принципу можно, только выводите в ячейки.
0 |
6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
|
30.03.2017, 11:04 [ТС] |
14 |
Hugo121, а можете сказать, я видел на одном сайте они выгружают словарь вот таким способом
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
30.03.2017, 11:10 |
15 |
Так и тут можно так выгружать внутренние словари (для внешнего итемы — это не значения, а объекты, поэтому так не пойдёт).
0 |
6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
|
30.03.2017, 11:16 [ТС] |
16 |
Hugo121, все большое спасибо
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
30.03.2017, 11:32 |
17 |
Можно выгрузить ключи в массив, его процедурой отсортировать (есть уже готовые разные), затем перебором этого массива извлекать итемы и всё писать на лист, или куда угодно.
0 |
6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
|
30.03.2017, 11:44 [ТС] |
18 |
Hugo121, а сортировать сам словарь это сложнее?
0 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
30.03.2017, 11:55 |
19 |
Словарь несортируется, там нельзя поменять позицию элементу. Да и как выше я уже говорил — эта позиция не гарантируется. Добавлено через 6 минут
0 |
6 / 6 / 0 Регистрация: 02.06.2014 Сообщений: 65 |
|
30.03.2017, 12:50 [ТС] |
20 |
Hugo121, т.е. порядка в словаре нет? я думал они стоят в порядке их добавления
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
30.03.2017, 12:50 |
20 |