Vba excel dictionary of dictionaries

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

Shan's user avatar

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

omegastripes's user avatar

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

PaulG's user avatar

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
Регистрация: 01.01.1970

Коллеги,

Подскажите, есть ли возможность добавления словаря в качестве значения в другой словарь?

К примеру есть основной словарь: ГЛ_СЛОВАРЬ (Ключ1: Значение1; Ключ2 : Значение2; …)

Вместо Значение1, Значение2, … должны быть словари. В итоге хотелось бы увидеть следующее:

ГЛ_СЛОВАРЬ (Ключ1: ВЛ_СЛОВАРЬ(Ключ1_1: Значение 1, …); Ключ2 :  ВЛ_СЛОВАРЬ(Ключ2_2: Значение 1, …); …)

Если есть такая возможность, то каким образом можно заполнить такую структуру и как к ней обращаться?

 

что мешает? добавляйте

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

Василий

Пользователь

Сообщений: 29
Регистрация: 01.01.1970

#3

27.04.2022 07:23:10

Примерно получается такой кусочек кода, но он не рабочий:

Код
Sub dict_check()
    
    Dim i As Long, i2 As Long
    Dim my_dict As Dictionary
    Dim my_dict2 As Dictionary
    Dim range1 As range
    
    range("K1:Q5").Select
    Set range1 = Selection
    
    Set my_dict = New Dictionary

'здесь я заполняю основной словарь и вложенный словарь    
    For i = 3 To range1.Rows.count
        Set my_dict2 = New Dictionary
        For i2 = 7 To range1.Columns.count
            my_dict2.Add range1.Cells(1, i2), range1.Cells(i, i2)
        Next i2
        my_dict.Add range1.Cells(i, 1), my_dict2
    Next i
    
'здесь я пробую прочитать вложенный словарь в основной
    Set my_dict2 = my_dict.Item("...")
    MsgBox my_dict2.Items
  
End Sub
 

Василий

Пользователь

Сообщений: 29
Регистрация: 01.01.1970

Т.е. я не совсем понимаю, как правильно вложить словарь во внутрь и как его при необходимости оттуда взять…

 

но вы хоть понимаете что вы хотите вложить в словари?
вот и обьясните что, на конкретном файле-примере, а вам покажут как это сделать
по не работающему коду трудно угадать идею (для чего он написан) или не интересно
(зачем угадывать, если можно просто прочитать описание задачи)

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

Василий, файл с кодом и данными

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Бахтиёр

Пользователь

Сообщений: 1930
Регистрация: 15.01.2016

Excel 365

#7

27.04.2022 09:46:26

Код
Sub ddd()
Dim dic As New Dictionary
mas = Range("A2:C10").Value
For i = 1 To UBound(mas)
    If Not dic.Exists(mas(i, 1)) Then dic.Add mas(i, 1), New Dictionary
    If Not dic(mas(i, 1)).Exists(mas(i, 2)) Then dic(mas(i, 1)).Add mas(i, 2), New Dictionary
    dic(mas(i, 1))(mas(i, 2))(mas(i, 3)) = ""
Next
For Each x In dic
    For Each y In dic(x)
        t = t & vbLf & x & ": " & y & " - " & Join(dic(x)(y).Keys, ", ")
    Next
Next
MsgBox t
End Sub

Прикрепленные файлы

  • Image 27-04-2022 11-40-26.jpg (194.52 КБ)
  • форум.xlsm (18.53 КБ)

Изменено: Бахтиёр27.04.2022 09:47:16

 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

Ну раз решение есть, то добавлю, что иногда может быть удобнее использовать массив словарей aDic() As Dictionary

Изменено: Jack Famous27.04.2022 10:20:37

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Василий

Пользователь

Сообщений: 29
Регистрация: 01.01.1970

#9

27.04.2022 14:20:16

Коллеги,

Спасибо за Ваш труд.

В итоге остановился на варианте, который я описал в самом начале.
Идею я максимально попытался изложить в заголовке. К сожалению примеры с файлами я не могу выкладывать в открытые доступы, да и в них просто гигантское количество данных.

Меня интересовало как именно в словарь, в значение его ключа включить еще один словарь. Почему не массив, потому что со словарем проще работать, там не нужно делать циклы для перебора значений.

Оказалось, что код, который я написал не корректно работал из-за разницы в типах данных.

Код
...                                        
      For i2 = 7 To range1.Columns.Count                                     
          my_dict2.Add CStr(range1.Cells(1, i2)), CStr(range1.Cells(i, i2))
      Next i2
      If my_dict.Exists(CStr(range1.Cells(i, 1))) = False Then               
          Set my_dict.Item(CStr(range1.Cells(i, 1))) = my_dict2 
      End if       
...

Так вот, проблема была в том, что значение ключа в словарь нужно было вставлять, предварительно преобразовав его в текстовый формат.

После этого все завелось :-)

 

New

Пользователь

Сообщений: 4581
Регистрация: 06.01.2013

#10

27.04.2022 20:34:44

Цитата
Василий написал:
К сожалению примеры с файлами я не могу выкладывать в открытые доступы, да и в них просто гигантское количество данных.

— скажите любое слово из русского языка?
— я не могу вам сказать PIN код моей банковской карты.
— вы не поняли, скажите вообще любое слово
— я же вам сказал, я не могу вам сказать PIN код от своей банковской карты!
так и вы…
Вы думаете Бахтиёр файл со своей работы выложил на форум? На форум никогда не нужно выкладывать свои рабочие файлы, а только небольшие примеры, а реальные конфиденциальные данные нужно заменять на апельсины, мандарины, яблоки, бабочки и т.д.

Изменено: New27.04.2022 23:25:37

 

Василий

Пользователь

Сообщений: 29
Регистрация: 01.01.1970

New,
Бахтиер в отличии от Вас заморочился и предложил свое решение, за что этому пользователю огромное уважение и благодарность. Получается, для него было достаточно вводных данных и его решение может абстрактно подходить для решения многих задач, не только конкретной.

А Вы просто флудите.

 

Msi2102

Пользователь

Сообщений: 3137
Регистрация: 31.03.2014

#12

28.04.2022 07:12:58

Цитата
Василий написал:
Бахтиер в отличии от Вас заморочился и предложил свое решение

Ну давайте начнём с того, что заморочиться должны были Вы, а не помогающий. Вы правила форума для начала почитайте и подумайте, почему у вас так мало ответов с решениями. И вообще удивительно, что эта тема просуществовала так долго. С таким названием, модераторы, как правило их удаляют.

Цитата
Василий написал:
его решение может абстрактно подходить для решения многих задач, не только конкретной.

Оно конечно может подходить, но в данной ветке должен быть поставлен конкретный вопрос, что именно не получается, и это также должно быть отражно в названии темы (что кстати тоже описано в правилах форума и модераторы за этим строго следят) , а не задавать филосовские вопросы, о проблемах словаря в словаре.

 

БМВ

Модератор

Сообщений: 21378
Регистрация: 28.12.2016

Excel 2013, 2016

Все остановились!
Название темы условно пригодное. Ну назовем «Использование словаря как элемента словаря»  — сильно не изменится
Василий,  пример сделать из нескольких строк , с данными не конф. это обычно несложно и по правила форума задача ТС а не помогающих.

По вопросам из тем форума, личку не читаю.

 

Jack Famous

Пользователь

Сообщений: 10848
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

Msi2102, пусть сидит теперь и ждёт помогающих, которые всё за него сделают  :D

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Александр Моторин

Пользователь

Сообщений: 958
Регистрация: 31.12.2012

#15

02.05.2022 08:06:03

Код
        If Not oUL_Dp.exists(t) Then 'если ещё нет ключа
            Set DP = CreateObject("Scripting.Dictionary"): DP.CompareMode = 1 'создаём субсловарь
            DP(domd) = r
            Set oUL_Dp(t) = DP
        Else 'если ключ есть
            oUL_Dp(t)(domd) = r
        End If

кусок кода из моей программы
словарь словарей   oUL_Dp
 

02-25-2014, 06:18 PM


#1

Dodo123 is offline


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 Dictionary

where 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

Dodo123 is offline


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

Dodo123 is offline


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

Quote Originally Posted by Dodo123
View Post

… 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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by shg
View Post

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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by kalak
View Post

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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Reiterative post — content was removed


02-26-2014, 11:18 AM


#11

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by shg
View Post

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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by shg
View Post

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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by shg
View Post

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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by shg
View Post

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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by shg
View Post

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

Dodo123 is offline


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

Dodo123 is offline


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 121

Sharing 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

Dodo123 is offline


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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by nilem
View Post

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

Dodo123 is offline


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

Dodo123 is offline


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

Quote Originally Posted by Dodo123
View Post

…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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by nilem
View Post

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

Dodo123 is offline


Registered User


Re: Creating Dictionary of Dictionaries

Quote Originally Posted by nilem
View Post

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


Студворк — интернет-сервис помощи студентам

Здравствуйте.
Я долго время пытался создать словарь словарей, перечитал различные методы предложенные тут на форуме, поэкспериментировал, но увы ни чего не получилось.
Если коротко, в фале есть 4 стр, мне нужно сделать поиск в 3 стр(кроме 1), найти соответствие номера заявки к лаб номеру(ищу заявку прибавляю к ней 1 столбеец) и с мг/дм.
должно получиться как-то так
{ключ-лаб номер;итем-[ключ-элемент(название стр);итем-с,мг/дм3)]}
прошу вашей помощи с кодом словарей, что-то я совсем запутался как их формировать
P.S. с vba только знакомлюсь и пользуюсь модулем 2, который имеется в книге



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 как решение

Решение

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  Dim a(), i&, Dic As Object, Dic2 As Object, t$, x&, y&
    a = [a1:k20].Value
    Set Dic = CreateObject("Scripting.Dictionary"): Dic.CompareMode = 1
 
    For i = 1 To UBound(a)
        t = a(i, 11)
        If Not Dic.exists(t) Then 'если ещё нет ключа
 
            Set Dic2 = CreateObject("Scripting.Dictionary"): Dic2.CompareMode = 1 'создаём субсловарь
            Dic2.Add a(i, 8), New Collection 'с ключём и № строки
            Dic2.Item(a(i, 8)).Add i: Dic.Add t, Dic2
 
        Else 'если ключ есть
            Set Dic2 = Dic.Item(t) 'извлекаем субсловарь
            
            If Not Dic2.exists(a(i, 8)) Then 'если в субсловаре нет субключа
                Dic2.Add a(i, 8), New Collection 'добавляем субключ с коллекцией
            End If
            Dic2.Item(a(i, 8)).Add i 'добавляем № строки
            
            Set Dic.Item(t) = Dic2 'заносим субсловарь
        End If
    Next

Добавлено через 58 секунд
но можно и короче

Добавлено через 1 минуту
Как-то так

Visual Basic
1
2
3
4
5
6
7
        If Not oUL_Dp.exists(t) Then 'если ещё нет ключа
            Set DP = CreateObject("Scripting.Dictionary"): DP.CompareMode = 1 'создаём субсловарь
            DP(domd) = r
            Set oUL_Dp(t) = DP
        Else 'если ключ есть
            oUL_Dp(t)(domd) = r
        End If



1



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

30.03.2017, 08:43

3

Лучший ответ Сообщение было отмечено kronos_o_0 как решение

Решение

Я так делал в другой задаче:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Sub PereborFailov2() ' словарь в словаре
    Dim a, i&, t$, Dic As Object, Dic2 As Object
    Dim el, col
    
    a = Range("C3", Cells(Rows.Count, "A").End(xlUp)).Value
    Set Dic = CreateObject("Scripting.Dictionary")
    With Dic
        .CompareMode = 1
        For i = 1 To UBound(a)
            t = a(i, 1)
            If Not .exists(t) Then .Add t, CreateObject("Scripting.Dictionary")
            .Item(t).Item(a(i, 2) & "|" & a(i, 3) & "|" & i) = 0&
            
        Next
    End With
    
    For Each el In Dic.keys
        Debug.Print "Открываем файл " & el
        Set Dic2 = Dic.Item(el)
        For Each col In Dic2.keys
            Debug.Print "Ищем данные " & col '& "|" & Dic2.Item(col)
        Next
        Debug.Print "Закрываем файл " & el
    Next
 
End Sub



1



kronos_o_0

6 / 6 / 0

Регистрация: 02.06.2014

Сообщений: 65

30.03.2017, 09:32

 [ТС]

4

Alex77755, я пытался сделать на подобие первого, но не совсем понял, там второй словарь вкладывают в коллекцию?
Hugo121, и это тоже пробовал он у меня всегда ругается на .item не понимаю в чем дело. Можете объяснить эти строчки?

Цитата
Сообщение от Hugo121
Посмотреть сообщение

.Item(t).Item(a(i, 2) & «|» & a(i, 3) & «|» & i) = 0&

вот что у меня получилось, но я не могу обратится к Dic через .item

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
For c = 1 To lcp
     If InStr(1, .Cells(c, r), ndz, vbTextCompare) > 0 Then
         With shi
         ky = .Cells(c, 2).Value
         it = .Cells(c, 6).Value
         End With
          t = nsh
          If Not Dic.exists(t) Then
          Set Dic2 = CreateObject("Scripting.Dictionary"): Dic2.CompareMode = 1
          Dic2(ky) = it
          Set Dic(t) = Dic2
          Else
          Dic(t)(ky) = it
          End If                                        
     End If
Next c



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

30.03.2017, 09:46

5

У меня на итем не ругается, да и у Вас скорее всего ругается на выход за пределы массива.
В той строке в словарь словаря по ключу t добавляется ключ a(i, 2) & «|» & a(i, 3) & «|» & i



0



kronos_o_0

6 / 6 / 0

Регистрация: 02.06.2014

Сообщений: 65

30.03.2017, 09:50

 [ТС]

6

Цитата
Сообщение от Hugo121
Посмотреть сообщение

Visual Basic
1
2
3
4
5
6
7
8
For Each el In Dic.keys
* * * * Debug.Print "Открываем файл " & el
* * * * Set Dic2 = Dic.Item(el)
* * * * For Each col In Dic2.keys
* * * * * * Debug.Print "Ищем данные " & col '& "|" & Dic2.Item(col)
 * * * *Next
* * * * Debug.Print "Закрываем файл " & el
* * Next

вставил эту часть, показало что словарь заполнен ключ[ключ, но итем второго словаря пуст]
т.е. как просто 1 словарь, как проверить заполненность словаря-словарей



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

30.03.2017, 10:00

7

Цитата
Сообщение от kronos_o_0
Посмотреть сообщение

как проверить заполненность словаря-словарей

тут что пишет?

Цитата
Сообщение от kronos_o_0
Посмотреть сообщение

Debug.Print «Ищем данные » & col



0



6 / 6 / 0

Регистрация: 02.06.2014

Сообщений: 65

30.03.2017, 10:07

 [ТС]

8

Цитата
Сообщение от Hugo121
Посмотреть сообщение

тут что пишет?

Открываем файл литий
Ищем данные 1
Ищем данные 2
Ищем данные 8
Закрываем файл литий
Открываем файл аммоний
Ищем данные 2
Ищем данные 1
Ищем данные 6
Закрываем файл аммоний
Открываем файл калий
Ищем данные 3
Ищем данные 2
Ищем данные 1
Закрываем файл калий
Закрываем файл калий



0



6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

30.03.2017, 10:13

9

Ну так вот же — у лития в словаре 1, 2 и 8, у аммония 2, 1, 6 и т.д.
А все эти литии/аммонии в первичном словаре.

Добавлено через 2 минуты
Можно на паузе посмотреть заполнение словарей в окнах Locals или Watches (в последнем можно посмотреть не только ключи, но и итемы).



0



6 / 6 / 0

Регистрация: 02.06.2014

Сообщений: 65

30.03.2017, 10:13

 [ТС]

10

Цитата
Сообщение от Hugo121
Посмотреть сообщение

Ну так вот же — у лития в словаре 1, 2 и 8, у аммония 2, 1, 6 и т.д.

да тут все правильно, но нет значений у 1,2,8 и т.д., у них должны быть еще
получается литий[1-знач,2-знач,8-знач]
второй словарь не формируется, должно быть же три значения
элемент-лаб№-значение
аа, это я туплю, он же показывает только ключи



0



Hugo121

6875 / 2807 / 533

Регистрация: 19.10.2012

Сообщений: 8,562

30.03.2017, 10:27

11

Да, в той реализации у всех внутренних значение 0, но можно изменить как угодно, а вывести можно если убрать апостроф в строке

Visual Basic
1
Debug.Print "Ищем данные " & col '& "|" & Dic2.Item(col)



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, а можете сказать, я видел на одном сайте они выгружают словарь вот таким способом
Cells(1, 1).Resize(, .Count) = .Keys
Cells(2, 1).Resize(, .Count) = .Items
почему он не работает для данной ситуации?



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

Понравилась статья? Поделить с друзьями:
  • Vba excel dictionary keys
  • Vba excel destination range
  • Vba excel delay что это
  • Vba excel define constant
  • Vba excel date функция